为什么我会ImportError: cannot import name 'BeautifulSoup'
line 1, in <module>
from bs4 import BeautifulSoup
ImportError: cannot import name 'BeautifulSoup'
是否已安装?
pip install --upgrade --force-reinstall beautifulsoup4
Collecting beautifulsoup4
Using cached beautifulsoup4-4.6.0-py3-none-any.whl
Installing collected packages: beautifulsoup4
Found existing installation: beautifulsoup4 4.6.0
Uninstalling beautifulsoup4-4.6.0:
Successfully uninstalled beautifulsoup4-4.6.0
Successfully installed beautifulsoup4-4.6.0
出现如此。
答案 0 :(得分:3)
不要将文件命名为bs4.py
Python有一个列表,它将检查模块,来自documentation:
导入名为
spam
的模块时,解释程序首先进行搜索 对于具有该名称的内置模块。如果没有找到,则搜索 对于由。给出的目录列表中名为spam.py
的文件 变量sys.path
。sys.path
已从以下位置初始化:
- 包含输入脚本(或当前目录)的目录。
PYTHONPATH
(目录名列表,语法与shell变量PATH
相同)。- 依赖于安装的默认值。
在您的情况下,它在执行它的同一目录中找到了一个名为bs4.py
的文件,并且由于它与您尝试导入的内容相匹配 - Python停止搜索其余目录。
由于您自己的bs4.py
不包含对象BeautifulSoup
,因此会出现导入错误。
通过仔细命名文件可以避免这种名称冲突;它在某些情况下确实有用(例如当你试图模拟或覆盖某些模块时);但这不是这种情况。