python 脚本请求post数据

本文章讲解使用 python 将从服务器post后返回的数据进行解析处理。

包含:


  •     python 读取csv文本
  •     python 日期时间格式转换
  •     python requests 的post 
  •     python解析json嵌套的数据
  •     python保存数据到文本

pytho通过reader 读取csv文件,并可以读取指定的某行数据。

#打开excel
with open('farmwork_datas3_8.csv','rt') as csvfile:
    reader = csv.reader(csvfile)
    for i,rows in enumerate(reader):
        if(i==470): #读取470行

           row = rows
            print(row[0]) #读取第一列数据

  •     python 日期时间格式转换

通过time.strptime()进行任意格式的转换。


startTime = "2021/08/23  23:33"

# 转为时间数组
            timeArray = time.strptime(startTime, "%Y/%m/%d %H:%M")
            beginTime = time.strftime("%Y%m%d%H%M%S", timeArray)
            
最后 beginTime =20210823230000

  •     python requests 的post 

python中使用post的时候导入 requests的库,没有时使用 pip install requests进行安装。

headers = {
    'User-Agent': 'Apipost client Runtime/+https://www.apipost.cn/',
    'Content-Type': 'application/x-www-form-urlencoded',
}
 data = {'ql': 'select `02`,`03`,`14` from farm_can#can where startRowKey = \'%s\' and stopRowKey = \'%s\' and `2601` = 0' %(startRowKey,stopRowKey)
           }

response = requests.post('http://172.16.1.10:10001/hbase/query', headers=headers, data=data)


data是类似sql的语句。

  •     python解析json嵌套的数据

从requests 的post 后返回的数据格式为json .


d={
        "status": 0,
        "data": [
                {
                        "02": 2059,
                        "03": "小白",
                        "14": "男",
                },
                {
                        "02": 2067,
                        "03": "小黑",
                        "14": "男",
                      
                }
        ]
}
            

result = json.loads(response.text)
            code = (result.get('status'))
            if code ==0:
                name= jsonpath.jsonpath(result,"$..03")
                id= jsonpath.jsonpath(result,"$..02")
                cnt =len(name)



通过上面的方法就可以得到所有的name .不过如果需要将name和id 对应起来组成 "id,name"的格式存到文件中,还需要做一下处理。


  python保存数据到文本

file = open(path + startRowKey+".csv", 'w')
                file.write("Longitude,latitude\r\n")
                for i in range(1,cnt):
                        combin = "%s,%s\r\n" % (lnt[i],lat[i])
                        #print(combin)
                        file.write(combin)
                file.close()





最后全部的 python文件为 read_works.py 如下:


您需要先登录才能查看隐藏内容

sitemap