user9135283
user9135283

Reputation:

ImportError: cannot import name 'BeautifulSoup'

Why am I getting ImportError: cannot import name 'BeautifulSoup'

  line 1, in <module>
        from bs4 import BeautifulSoup
    ImportError: cannot import name 'BeautifulSoup'

Is it installed?

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

Appears so.

Upvotes: 2

Views: 4055

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174614

Don't name your file bs4.py


Python has a list of places it will check for modules, from the 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.

In your case, it found a file called bs4.py in the same directory where it was being executed, and since it matches what you are trying to import - Python stopped searching the rest of the directories.

As your own bs4.py does not contain the object BeautifulSoup, you get the import error.

This sort of name clashing can be avoided by careful naming of your files; it does come in useful in some cases (for example when you are trying to mock or override some modules); but that is not the case here.

Upvotes: 5

Related Questions