为什么通过simplejson的Google API查询返回“responseData”: null?
我正在尝试用Python和simplejson来抓取Google搜索的第一个结果,但我发现自己无法像网上很多示例那样访问搜索结果。这里有一段代码:
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (query)
search_results = urllib.urlopen(url)
json = simplejson.load(search_results)
try:
results = json['responseData']['results'] # always fails at this line
first_result = results[0]
except:
print "attempt to set results failed"
当我在浏览器中打开 http://ajax.googleapis.com/ajax/services/search/web?v=1.0&stackoverflow(或者把%s替换成其他内容)时,显示的内容是 "{"responseData": null, "responseDetails": "clip sweeping", "responseStatus": 204}." 这是不是意味着我在Python中访问Google搜索结果的方式有问题,除了使用这个看起来是空的responseData之外,还有其他方法吗?
1 个回答
2
你漏掉了 &q= 这个部分。你还应该考虑使用一个 api-key(应用程序接口密钥)。可以参考这个链接了解更多信息:http://code.google.com/intl/de/apis/ajaxsearch/documentation/。另外,简单的字符串拼接是行不通的,你需要对参数进行转义处理。
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q= ' + urllib.quote_plus(query)