2 python beautifulsoup python-3.x
为什么我得到 ImportError: cannot import name 'BeautifulSoup'
line 1, in <module>
from bs4 import BeautifulSoup
ImportError: cannot import name 'BeautifulSoup'
Run Code Online (Sandbox Code Playgroud)
是否已安装?
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
Run Code Online (Sandbox Code Playgroud)
看来如此。
不要命名您的文件 bs4.py
Python 有一个将检查模块的位置列表,来自文档:
当
spam导入命名的模块时,解释器首先搜索具有该名称的内置模块。如果未找到,它将搜索spam.py在变量给出的目录列表中命名的文件sys.path。sys.path从这些位置初始化:
- 包含输入脚本的目录(或当前目录)。
PYTHONPATH(目录名称列表,语法与 shell 变量相同PATH)。- 依赖于安装的默认值。
在您的情况下,它bs4.py在执行它的同一目录中找到了一个文件,并且由于它与您尝试导入的内容匹配 - Python 停止搜索其余目录。
由于您自己的bs4.py不包含 object BeautifulSoup,您会收到导入错误。
通过仔细命名文件可以避免这种名称冲突;它在某些情况下确实很有用(例如,当您尝试模拟或覆盖某些模块时);但这里的情况并非如此。