Last modified: Mar 06, 2025 By Alexander Williams

Fix Python NameError: Name 'BeautifulSoup' Not Defined

Encountering a NameError in Python can be frustrating. One common error is NameError: Name 'BeautifulSoup' Not Defined. This article explains why this error occurs and how to fix it.

What Causes the NameError?

The NameError occurs when Python cannot find the name BeautifulSoup in the current scope. This usually happens because the BeautifulSoup class is not imported correctly.

For example, if you try to use BeautifulSoup without importing it, you'll get this error:


soup = BeautifulSoup(html_content, 'html.parser')

This code will raise a NameError because BeautifulSoup is not defined.

How to Fix the NameError

To fix the NameError, you need to import the BeautifulSoup class from the bs4 module. Here's how you can do it:


from bs4 import BeautifulSoup

html_content = "Hello, World!"
soup = BeautifulSoup(html_content, 'html.parser')
print(soup.h1.text)

In this example, the BeautifulSoup class is imported correctly, and the code runs without errors.

Common Mistakes

Sometimes, the error occurs because of a typo or incorrect import statement. For example, if you mistakenly import beautifulsoup instead of BeautifulSoup, you'll get the same error.


from bs4 import beautifulsoup  # Incorrect import

soup = BeautifulSoup(html_content, 'html.parser')  # This will raise a NameError

Always ensure that you import the correct class name, which is BeautifulSoup.

Using Virtual Environments

If you're working in a virtual environment, make sure that the bs4 module is installed. You can install it using pip:


pip install beautifulsoup4

If the module is not installed, Python won't be able to find BeautifulSoup, leading to a NameError.

Related Errors

Similar errors can occur with other Python modules. For example, you might encounter NameError: Name 'deque' Not Defined or NameError: Name 'Counter' Not Defined. The solutions are often similar: ensure the correct module is imported.

Conclusion

The NameError: Name 'BeautifulSoup' Not Defined is a common issue in Python. It usually occurs because the BeautifulSoup class is not imported correctly. By ensuring the correct import statement and installing the necessary module, you can easily fix this error.

For more information on handling similar errors, check out our guides on NameError: Name 'datetime' Not Defined and NameError: Name 'collections' Not Defined.