【问题标题】:Beautiful Soup Unicode encode errorBeautiful Soup Unicode 编码错误
【发布时间】:2011-02-07 07:07:50
【问题描述】:

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

如何调试?

当我删除对打印功能的调用时,我没有收到任何错误。

【问题讨论】:

    标签: python unicode beautifulsoup


    【解决方案1】:

    str(para) 内置函数正在尝试对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") 应用于每个列表元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      • 2014-05-31
      • 2021-01-24
      • 2017-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多