Beautiful Soup Unicode 编码错误

12 投票
1 回答
10759 浏览
提问于 2025-04-15 21:31

我正在用一个特定的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)

我该怎么调试这个问题呢?

当我去掉调用打印函数的那部分时,就没有任何错误了。

1 个回答

2

内置的 str(para) 函数试图使用默认的 ascii 编码来处理 para 中的 Unicode 字符。这是在调用 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")

撰写回答