views:

367

answers:

1

I am trying the following code with a particular HTML file

from BeautifulSoup import BeautifulSoup
import re
import codecs
import sys
f = open('test1.html')
html = f.read()
soup = BeautifulSoup(html)
body = soup.body.contents
para = soup.findAll('p')
print str(para).encode('utf-8')

I get the following error:

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

How do I debug this?

I do not get any error when I remove the call to print function.

+2  A: 

The str(para) builtin is trying to use the default (ascii) encoding for the unicode in para. This is done before the encode() call:

>>> s=u'123\u2019'
>>> str(s)
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 3: ordinal not in range(128)
>>> s.encode("utf-8")
'123\xe2\x80\x99'
>>> 

Try encoding para directly, maybe by applying encode("utf-8") to each list element.

gimel