Python中googlesearch无法导入search及运行报错求助
解决方案
解决 ImportError: cannot import name 'search' from 'googlesearch'
- 卸载当前安装的同名包:
pip uninstall googlesearch - 安装官方维护的替代包(结构更稳定,适配最新Python版本):
pip install googlesearch-python - 重新执行导入语句:
from googlesearch import search
解决 IndexError: list index out of range
这个错误是因为Google搜索页面的HTML结构更新,旧版本模块里的选择器无法定位到结果总数元素。解决方式:
- 如果你安装了上面的
googlesearch-python,这个问题已经被修复,直接调用search函数即可,无需修改代码。 - 若坚持使用旧版本模块,手动修改
googlesearch.py文件:- 打开路径
...\AppData\Roaming\Python\Python39\site-packages\googlesearch\googlesearch.py - 找到
GoogleSearch类中的TOTAL_SELECTOR属性,将其替换为当前Google搜索页面中显示结果总数的元素选择器(可通过浏览器开发者工具查看,当前常用值为#result-stats):class GoogleSearch(Search): TOTAL_SELECTOR = "#result-stats" # 其余代码保持不变 - 同时修改获取文本的代码,适配新元素的结构:
totalText = soup.select(GoogleSearch.TOTAL_SELECTOR)[0].text.strip()
- 打开路径
内容的提问来源于stack exchange,提问作者Arun
相关产品推荐
相关产品推荐

