6

所以,我想使用 Kenneth 的优秀请求模块。在尝试使用Freebase API时偶然发现了这个问题。

基本上,他们的 API 是这样的:

https://www.googleapis.com/freebase/v1/mqlread?query=...

作为一个查询,他们需要一个 JSON 对象,这里会返回一个包含他们的国家和酒精百分比的葡萄酒列表

[{
  "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

4

1 回答 1

7

这个对我有用。这是我所做的:

>>> 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'

于 2012-05-08T17:35:04.050 回答