为什么我得到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
出现。
不命名您的文件bs4.py
python有一个将从文档中查看模块的地点列表:
导入名为
spam
的模块时,解释器首先搜索 对于具有该名称的内置模块。如果找不到的话,它将搜索 对于一个名为spam.py
的文件,在由 可变sys.path
。sys.path
是从这些位置初始化的:
- 包含输入脚本(或当前目录)的目录。
PYTHONPATH
(目录名称的列表,具有与Shell变量PATH
相同的语法)。- 依赖安装的默认值。
在您的情况下,它在执行它的同一目录中找到了一个名为 bs4.py
的文件,并且由于它与您要导入的内容匹配 - Python停止搜索其余的目录。
由于您自己的bs4.py
不包含对象BeautifulSoup
,因此您会收到导入错误。
可以通过仔细命名文件来避免这种名称的冲突;在某些情况下,它确实很有用(例如,当您试图模拟或覆盖某些模块时);但这里不是这样。