我正在尝试使用特定的 HTML 文件编写以下代码
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')
我收到以下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 9: ordinal not in range(128)
我该如何调试?
当我删除对 print 函数的调用时,我没有收到任何错误。
最佳答案
str(para)
builtin 正在尝试对 para
中的 unicode 使用默认 (ascii
) 编码。
这是在 encode()
调用之前完成的:
>>> 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'
>>>
尝试直接对 para
进行编码,也许可以对每个列表元素应用 encode("utf-8")
。
关于python - Beautiful Soup Unicode 编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2627071/