问题描述
我是Python的新手,正尝试从URL中获取user.csv文件中每个用户的响应,返回JSON消息,然后将其解析为CSV。 我不确定要在返回部分中放入什么或如何拆分消息。 这是我收到HTTP请求时返回给我的消息的示例:
{“ msg”:{“ mes”:“四个”,“ high”:1230,“ low”:0}}}”
这是我到目前为止的内容,但出现错误:
TypeError:预期的字符串或缓冲区
import requests
import json
import csv
def getRows(data):
return []
url = 'http://test_url'
with open('user.csv', 'rU') as data_file:
data = csv.DictReader(data_file)
for row in data:
current_user = row['mdn']
r = requests.get(url)
data = json.loads(data)
fname = "mydata.csv"
with open(fname,'wb') as outf:
outcsv = csv.writer(outf)
outcsv.writerows(getRows(data))
1楼
利用您提供的信息,您可以执行以下操作:
import requests
import csv
url = 'http://test_url'
with open('user.csv', 'rU') as data_file:
data = csv.DictReader(data_file)
for row in data:
current_user = row['mdn']
r = requests.get(url) # probably you also need to send current_user somehow. "r = requests.get(url+'?user='+current_user)" maybe?
string_json = r.text.encode('utf-8')
json = eval(string_json) # only use this command if you are sure that string_json only contains a valid json and no malicious code instead
with open('outputfile.csv','a') as outfile:
outfile.write(current_user+';'+json["msg"]["mes"]+';'+json["msg"]["high"]+';'+json["msg"]["low"]+'\n')
请提供有关HTTP请求使用情况和csv格式的更多信息,以获取更准确的答案