使用Pytrends API获取谷歌趋势时出现404错误的原因咨询
使用Pytrends API获取谷歌趋势时出现404错误的原因咨询
嘿,我来帮你排查这个404错误的问题!
你遇到这个报错的核心原因是:传给trending_searches方法的pn参数格式不对。Pytrends的trending_searches方法要求pn参数使用谷歌趋势认可的地区缩写代码,而不是你写的英文全称(比如kuwait)或者下划线分隔的名称(比如united_states)。当你用了错误的参数值时,Pytrends会请求一个不存在的谷歌趋势页面,自然就返回404错误了。
举个对应正确参数的例子:
- 美国对应的正确代码是
'us',不是'united_states' - 科威特对应的正确代码是
'kw',不是'kuwait' - 卡塔尔对应的正确代码是
'qa',不是'qatar'
下面是修改后的可运行代码:
import pytrends from pytrends.request import TrendReq pytrends = TrendReq(hl='en-US', tz=360) # 替换成正确的地区缩写代码 countries = ['us', 'kw', 'qa'] def trending_searches(country): data = pytrends.trending_searches(pn=country) print(data) country = 'kw' trending_searches(country) for country in countries: print(f'trend searches for: {country}') trending_searches(country)
如果你需要查其他国家的正确代码,可以参考Pytrends官方文档里的地区参数说明,或者直接打开谷歌趋势网页,切换到对应的地区后看URL里的geo参数值,那个就是你需要用的pn参数值哦。
备注:内容来源于stack exchange,提问作者mehdi bahanni




