所以,我想使用Kenneth'优秀的requests module。在尝试使用Freebase API时偶然发现了这个问题。
基本上,他们的API看起来像这样:
https://www.googleapis.com/freebase/v1/mqlread?query=...
作为一个查询,他们期望一个JSON对象,这里是return a list of wines with their country and percentage of alcohol:
[{
"country": null,
"name": null,
"percentage_alcohol": null,
"percentage_alcohol>": 0,
"type": "/food/wine"
}]
当然,在将它传递给URL之前,我们必须逃避这一点,所以实际的查询将如下所示:
fullurl = 'https://www.googleapis.com/freebase/v1/mqlread?query=%5B%7B%22percentage_alcohol%3E%22%3A+0%2C+%22country%22%3A+null%2C+%22type%22%3A+%22%2Ffood%2Fwine%22%2C+%22name%22%3A+null%2C+%22percentage_alcohol%22%3A+null%7D%5D'
现在,
r = requests.get(fullurl)
print r.status_code
>>> 400
因为网站声称它无法解析查询。
r2 = urllib2.urlopen(fullurl)
print r2.getcode()
>>> 200
这里没问题,我得到了适当的回报。有趣的是,
# This is the url of our requests.get request
print urllib2.urlopen(r.url).getcode()
>>> 200
为什么呢?我使用模块错了吗?或者它是requests
中的错误?
答案 0 :(得分:6)
它对我有用。这是我做的:
>>> params = [{"country": None,
... "name": None,
... "percentage_alcohol": None,
... "percentage_alcohol>": 0,
... "type": "/food/wine"
... }]
>>> import json
>>> params_json = json.dumps(params)
>>> import requests
>>> url = "https://www.googleapis.com/freebase/v1/mqlread?query=%s"
>>> r = requests.get(url % params_json)
>>> r.status_code
200
>>> content_json = json.loads(r.content)
>>> import pprint
>>> pprint.pprint(content_json)
{u'result': [{u'country': u'New Zealand',
u'name': u'2003 Cloudy Bay Sauvignon Blanc',
u'percentage_alcohol': 13.5,
u'type': u'/food/wine'},
{u'country': u'France',
u'name': u'G.H. Mumm Cordon Rouge Brut',
u'percentage_alcohol': 12.0,
u'type': u'/food/wine'},
....
为了简洁起见,我把剩下的休息了。有100个结果。 requests.__version__ == '0.10.6'