python - Beautiful Soup Unicode 编码错误

标签 python unicode beautifulsoup

我正在尝试使用特定的 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/

相关文章:

javascript - 跨域返回非unicode字符

C++ unicode UTF-16编码

python - beautifulsoup4 : placing a for loop unwrapping tags into a definition (python3)

python - 为什么 matplotlib 给出错误 [<matplotlib.lines.Line2D object at 0x0392A9D0>]?

python - 登录框架

MySQL 处理 utf8mb4_unicode_ci 的 unicode 文本

python - 如何在 Python BeautifulSoup 上有效地解析大型 HTML div 类和跨度数据?

python - 如何在 Python Argparse 中跳过位置参数

python - 如何在Windows的Docker中挂载卷?

python - 为什么我要从网页中提取的数据不在我的汤页面中?