views:

1857

answers:

1

With BeautifulSoup 3.1.0.1 and Python 2.5.2, and trying to parse a web page in French. However, as soon as I call findAll, I get the following error:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1146: ordinal not in range(128)

Below is the code I am currently running:

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html")
soup = BeautifulSoup(page, fromEncoding="latin1")
r = soup.findAll("table")
print r

Does anybody have an idea why?

Thanks!

UPDATE: As resquested, below is the full Traceback

Traceback (most recent call last):
  File "[...]\test.py", line 6, in <module>
    print r
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128)
+7  A: 

Here is another idea. Your terminal is not capable of displaying an unicode string from Python. The interpreter tries to convert it to ASCII first. You should encode it explicitly before printing. I don't know the exact semantics of soup.findAll(). But it is probably something like:

for t in  soup.findAll("table"):
    print t.encode('latin1')

If t really is a string. Maybe its just another object from which you have to build the data that you want to display.

unbeknown
It works! :D But what do you mean by "Your terminal is not capable of displaying an unicode string from Python.". I am running my script inside IDLE (Python Shell). This should work, isn't it?
Martin
A terminal has to tell the Python interpreter what characterset it uses. Usually this is done through an environment variable. I don't know how this is handled by IDLE.
unbeknown
print repr(t) is also useful. It's generally a good idea to repr() stuff you're outputting for debugging purposes so you can see exactly the type and any top-bit-set or control characters lurking in there, as well as not making your debug code throw more spurious exceptions.
bobince