BeautifulSoup报错TypeError: 'module' object is not callable 求助
报错根因
触发TypeError: 'module' object is not callable是因为导入语句写法错误:你写的import bs4 as BeautifulSoup是把整个bs4模块导入后重命名为BeautifulSoup,后续你写BeautifulSoup(...)时本质是尝试调用整个模块,而模块本身是不可被直接调用的。
另外两个容易混淆的点:
html.parser是Python标准库内置的HTML解析器,不需要额外通过pip安装,你手动安装的第三方同名html.parser包属于冗余安装,可能引发潜在环境冲突- 你提到其他项目相同代码能跑大概率是记忆偏差,正确的BeautifulSoup导入逻辑从来不是直接导入bs4模块
修正方案
- 先清理虚拟环境的冗余依赖:
执行pip uninstall -y html.parser卸载多余的第三方包,再执行pip install --upgrade beautifulsoup4确认你装的是官方维护的正确bs4版本(注意不要装名为bs4的废弃第三方包) - 替换错误的导入语句,修正后的完整代码如下:
import requests from bs4 import BeautifulSoup source = requests.get('https://docs.python.org/3/library/html.parser.html') soup = BeautifulSoup(source.text, 'html.parser') print(soup)
修正后不需要额外import html.parser,只要解析器参数传'html.parser'字符串,BeautifulSoup会自动调用标准库内置的对应解析器。
内容的提问来源于stack exchange,提问作者c0nfluks
相关产品推荐
相关产品推荐

