python - 导入错误: cannot import name 'BeautifulSoup'

标签 python python-3.x beautifulsoup

为什么我收到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 named spam.py in a list of directories given by the variable sys.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 variable PATH).
  • the installation-dependent default.

就您而言,它在执行它的同一目录中找到了一个名为 bs4.py 的文件,并且由于它与您尝试导入的内容匹配 - Python 停止搜索其余部分目录。

由于您自己的 bs4.py 不包含对象 BeautifulSoup,因此您会收到导入错误。

通过仔细命名文件可以避免这种名称冲突;它在某些情况下确实很有用(例如,当您尝试模拟或覆盖某些模块时);但这里的情况并非如此。

关于python - 导入错误: cannot import name 'BeautifulSoup' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47958281/

相关文章:

python - 在不同的实现中继承自 Tkinter Frame

python - 在元素之间添加逗号

python - 异步 : How to handle multiple open files OS error

python - 使用 NLP 让系统学习对文本进行分类

从子目录导入模块时Python出错

python - 使用 Python Beautifulsoup 循环遍历 HTML 标签进行网页抓取

javascript - 使用 BS4 抓取用 JS 编写的脚本

python - 如何在 BeautifulSoup 中保持 Django 模板代码的有效性

python - 如何概括文件函数以打开参数中提供的尽可能多的文本文件?

python - 删除python中继承的dict元素