我正在尝试编写一个python脚本,它将从http服务器检索值并将数据更改为csv格式,我使用httplib2库来预先形成请求,但我的问题是内容的返回是在application / x-www-form-urlencoded格式,我有用于将数据解析为dict的代码,但似乎无法用它作为这种字符串做任何事情,我知道它对于广泛的用户来说似乎很简单,如我似乎无法通过研究找到任何相关信息......
下面是一个示例代码,只是为了说明我正在尝试做的事情的类型和我的问题
import httplib2
http = httplib2.Http()
resp, content = http.request("http://example.com/foo/bar")
感谢您的帮助
btw我正在使用python 2.7,请求自然返回的格式是json
答案 0 :(得分:2)
如果您收到编码的回复,则可以使用urllib.unquote
将转义的字符替换为“实际”字符。完成后,您可以使用json
模块将字符串作为Python对象加载,然后使用csv
模块根据响应创建CSV。您的回复结构将决定如何在您的最终设置,但希望这将使您走上正确的道路:
In [1]: import csv
In [2]: import json
In [3]: import urllib
In [4]: json_resp = urllib.quote('[{"name": "John Doe", "age": 35}, {"name": "Jane Doe", "age": 33}]')
In [5]: json_resp # What I believe your response looks like
Out[5]: '%5B%7B%22name%22%3A%20%22John%20Doe%22%2C%20%22age%22%3A%2035%7D%2C%20%7B%22name%22%3A%20%22Jane%20Doe%22%2C%20%22age%22%3A%2033%7D%5D'
In [6]: resp = urllib.unquote(json_resp) #'Unquote' the response
In [7]: resp
Out[7]: '[{"name": "John Doe", "age": 35}, {"name": "Jane Doe", "age": 33}]'
In [8]: content = json.loads(resp) # Turn the resp into a Python object
In [9]: fieldnames = ('name', 'age') # Specify the order in which to write fields
In [10]: with open('mycsv.csv', 'wb') as f:
....: writer = csv.DictWriter(f, fieldnames)
....: writer.writeheader() # Python 2.7+
....: for item in content:
....: writer.writerow(item)
....:
....:
这将写一个类似于:
的CSVname,age
John Doe,35
Jane Doe,33