Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: module 'bs4' has no attribute 'BeautifulSoup'

Tags:

python-3.x

Traceback (most recent call last):
  File "bs4.py", line 1, in <module>
    import  bs4
  File "/home/mhadi/Desktop/bs4test/bs4.py", line 5, in <module>
    soup = bs4.BeautifulSoup(site,'lxml')
AttributeError: module 'bs4' has no attribute 'BeautifulSoup'

The code:

import  bs4
import urllib.request

site = urllib.request.urlopen('http://127.0.0.1:8000').read()
soup = bs4.BeautifulSoup(site,'lxml')
#for i in site: 
#    print(site[i])
print(soup)
like image 965
Mhadi Ahmed Avatar asked Jun 13 '26 21:06

Mhadi Ahmed


1 Answers

The problem is that your filename is bs4.py. Now if you write an import statement, Python will first look for local files with that name. So it assumes that your import bs4 refers to your own file. Your file will thus aim to import itself, but it obviously does not contain the desired module.

A quick fix is renaming the file. For instance into bs4tests.py. Then you can use import bs4.

Alternatively, you can for instance try to remove the local path, like:

import sys               # import sys package
old_path = sys.path[:]   # make a copy of the old paths
sys.path.pop(0)          # remove the first one (usually the local)
import bs4               # import the package
sys.path = old_path      # restore the import path
like image 75
Willem Van Onsem Avatar answered Jun 18 '26 00:06

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!