无法让 Google 的搜索 API 与 Python 配合使用



我正在使用谷歌自己的搜索API,但我一直得到403错误。密钥取自console.developers.google.com下的api &auth ->凭据,我使用浏览器密钥与任何引用。ID取自自定义搜索引擎的基本信息。

import requests
search = "https://www.googleapis.com/customsearch/v1"
key = "?key=MY_KEY"
id_ = "&cx=MY_ID"
query = "&q=test"
get = search + key + id_ + query
r = requests.get(get)
print(r)

我做错了什么?

我不知道这是否是您的问题的根源,但您可以更好地使用requests库。对于初学者,您可以将API密钥和CX值放入会话对象中,以便在后续请求中使用它们:

>>> import requests
>>> s = requests.Session()
>>> s.params['key'] = 'MY_KEY'
>>> s.params['cx'] = 'MY_CX'

您可以通过在params关键字中传递字典来传递额外的搜索参数,而不是自己构建URL:

>>> result = s.get('https://www.googleapis.com/customsearch/v1', 
... params={'q': 'my search string'})

这一切都为我工作:

>>> result
<Response [200]>
>>> print result.text
{
 "kind": "customsearch#search",
 "url": {
  "type": "application/json",
  "template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe
[...]

另外,值得检查的是,您已经为您的API密钥启用了搜索API。

您可以通过Python logging模块启用调试日志来准确地看到requests库正在做什么:

>>> import logging
>>> logging.basicConfig(level='DEBUG')
>>> result = s.get('https://www.googleapis.com/customsearch/v1', params={'q': 'openstack'})
DEBUG:requests.packages.urllib3.connectionpool:"GET /customsearch/v1?q=openstack&cx=0123456789123456789%3Aabcdefghijk&key=THIS_IS_MY_KEY HTTP/1.1" 200 13416

最新更新