使用API 在python中执行Google搜索,并通过KeyError返回

问题描述 投票:0回答:1

我在this answer中使用了完全相同的代码,但没有成功。

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'

然后我尝试删除密钥并查看结果是什么。

似乎没有任何名为“ items”的键

所以问题是:

我如何调整代码并获取排名在前20位的链接列表 Google搜索结果?

提前感谢。

桑德拉

python google-search google-search-api
1个回答
0
投票

当查询无结果时会发生这种情况。如果只有结果,它将归入res [“ items”]。由于没有结果,因此不会生成项目密钥。

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

请确保位于设置->基本(Tab)->搜索站点(部分)中的搜索引擎应用程序中“自定义搜索”的配置设置为“搜索整个网络,但强调包含站点”。

© www.soinside.com 2019 - 2024. All rights reserved.