Pytrends错误是由于缺少数据

2024-10-01 07:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用pytrendsrelated_queries()函数查找关键字列表的相关关键字,但是如果其中一个关键字没有足够的数据来提供相关查询,则进程将崩溃,并出现错误:

KeyError: "[u'query' u'value'] not in index"

在错误发生后,代码对任何关键字都不起作用,直到我关闭并重新启动内核,所以我没有成功地捕捉到错误。一个不起作用的例子是:

^{pr2}$

Tags: 数据函数代码in列表index进程value
1条回答
网友
1楼 · 发布于 2024-10-01 07:18:00

我能够通过为每次迭代重新建立连接来捕捉错误,虽然效率低下,但完成了任务: r = pd.DataFrame() s = pd.DataFrame() for i in listofwords: try: pytrend = TrendReq(google_username, google_password, custom_useragent='Pytrends') pytrend.build_payload(kw_list=[i]) Related_df = pytrend.related_queries() s = s.append(Related_df[i]['top'].head(3)) r = r.append(Related_df[i]['rising']['query'].head(3)) except: pass

相关问题 更多 >