简体   繁体   English

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

[英]Performing google search in python with API, returned with KeyError

I use exactly the same code in this answer , but it didn't work out.我在这个答案中使用了完全相同的代码,但没有成功。

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)

The result shows KeyError: 'items'结果显示KeyError: 'items'

Then I tried to remove the key and see what the result is.然后我试图删除密钥,看看结果是什么。

It seems like there aren't any keys named "items"似乎没有任何名为“项目”的键

So the question is:所以问题是:

How can I tweak the code and get a list of links ranked in the top 20 google search results?如何调整代码并获得在前 20 个谷歌搜索结果中排名的链接列表

Thanks in advance.提前致谢。

Sandra桑德拉

This happens when the query has no result.当查询没有结果时会发生这种情况。 If only it had results, it comes under res["items"].如果它有结果,它就属于 res["items"]。 Since you have no result, the items key is not generated.由于您没有结果,因此不会生成 items 键。

The custom search engine you created might be only accessible to very few URLs.您创建的自定义搜索引擎可能只能访问极少数 URL。 Thus the result might be empty.因此结果可能为空。

Make sure your configuration for "Custom Search" in your search engine app located at Setup -> Basic (Tab) -> Sites to Search (Section) is set to "Search the entire web but emphasize include site".确保您的搜索引擎应用程序中的“自定义搜索”配置位于设置 -> 基本(选项卡)-> 要搜索的站点(部分)设置为“搜索整个网络,但强调包含站点”。

Also for the code, instead of returning res["items] directly, check if res["items"] is present, else return None. Then KeyError exception won't happen.同样对于代码,不是直接返回 res["items],而是检查 res["items"] 是否存在,否则返回 None。然后不会发生 KeyError 异常。

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

只需更换您的退货:

return res.get('items', None)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM