M. Westerfeld
M. Westerfeld

Reputation: 1

Import error using BeautifulSoup

this is my first time asking a question here so please be gentle with me (I did try to find an answer to my problem, but couldn't). Also, I'm a complete noob in programming, I'm afraid. So, let's get to it:

I'd like to use the BeautifulSoup Library (v4.4) with the built-in Python v 2.7.6 on my Mac (10.10.4), however, after numerous attempts of installation using this method

python setup.py install

and this method (after having downloaded pip, of course)

pip install beautifulsoup4

I still get the following error whenever I try to run a very simple script such as this one (don't bother about it's stupidity)

import urllib

from bs4 import BeautifulSoup

fhand = urllib.urlopen('http://www.dr-chuck.com/page1.htm')

html=fhand.read()

soup = BeautifulSoup(html)

I get the following error message

Traceback (most recent call last):
File "bs4.py", line 3, in <module>
from bs4 import BeautifulSoup
File "/Users/mwesterfeld/Desktop/Python/bs4.py", line 3, in <module>
from bs4 import BeautifulSoup
ImportError: cannot import name BeautifulSoup

At first I thought it might be due to the fact that at some point I had installed Python 3.3 in addition to my system version of python. I used the procedure described here to uninstall it but unfortunately that didn't solve the problem.

Weirdly, if I open python using terminal and bring up a list of the modules I have installed "bs4" is among them.

Can anybody tell me what's wrong? Any help is much appreciated, thanks in advance!

Upvotes: 0

Views: 3162

Answers (1)

Chris Montanaro
Chris Montanaro

Reputation: 18202

The problem is that the script you are writing in has the same name as the module you are importing. Change your script name to something other than bs4.py and remove the bs4.pyc:

monty-macbook:~ monty$ python bs4.py
Traceback (most recent call last):
  File "bs4.py", line 2, in <module>
    from bs4 import BeautifulSoup
  File "/Users/monty/bs4.py", line 2, in <module>
    from bs4 import BeautifulSoup
ImportError: cannot import name BeautifulSoup
monty-macbook:~ monty$ mv bs4.py bs4new.py
monty-macbook:~ monty$ rm bs4.pyc
monty-macbook:~ monty$ python bs4new.py
/Library/Python/2.7/site-packages/bs4/__init__.py:166: UserWarning: No parser was explicitly specified, so I'm using the best available HTML parser for this system ("html.parser"). This usually isn't a problem, but if you run this code on another system, or in a different virtual environment, it may use a different parser and behave differently.

To get rid of this warning, change this:

 BeautifulSoup([your markup])

to this:

 BeautifulSoup([your markup], "html.parser")

  markup_type=markup_type))

Upvotes: 3

Related Questions