为什么我收到ImportError:无法导入名称“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
看起来是这样。
最佳答案
不要将文件命名为bs4.py
Python 有一个将检查模块的位置列表,来自 documentation :
When a module named
spam
is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file namedspam.py
in a list of directories given by the variablesys.path
.sys.path
is initialized from these locations:
- the directory containing the input script (or the current directory).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- the installation-dependent default.
就您而言,它在执行它的同一目录中找到了一个名为 bs4.py
的文件,并且由于它与您尝试导入的内容匹配 - Python 停止搜索其余部分目录。
由于您自己的 bs4.py
不包含对象 BeautifulSoup
,因此您会收到导入错误。
通过仔细命名文件可以避免这种名称冲突;它在某些情况下确实很有用(例如,当您尝试模拟或覆盖某些模块时);但这里的情况并非如此。
关于python - 导入错误: cannot import name 'BeautifulSoup' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958281/