使用API在python中执行google搜索,返回KeyError



我在这个答案中使用了完全相同的代码,但没有成功。

from googleapiclient.discovery import build
import pprint
my_api_key = "Google API key"
my_cse_id = "Custom Search Engine ID"
def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res['items']
results = google_search(
'stackoverflow site:en.wikipedia.org', my_api_key, my_cse_id, num=10)
for result in results:
pprint.pprint(result)

结果显示KeyError:'items'

然后我试着取下钥匙,看看结果如何

似乎没有任何名为"项目"的密钥

所以问题是:

如何调整代码并获得排名前20的链接列表谷歌搜索结果?

提前谢谢。

Sandra

当查询没有结果时会发生这种情况。如果它有结果就好了,它属于res["items"]。由于没有结果,因此不会生成items键。

您创建的自定义搜索引擎可能只能访问极少数URL。因此,结果可能为空。

确保位于设置->基本(选项卡(->要搜索的网站(部分(的搜索引擎应用程序中的"自定义搜索"配置设置为"搜索整个网站,但强调包括网站"。

同样,对于代码,不是直接返回res["items],而是检查res["items"]是否存在,否则返回None。这样KeyError异常就不会发生。

if "items" in res.keys(): 
return res["items"] 
else: 
return None

只需替换您的退货:

return res.get('items', None)

最新更新