【问题标题】:UnicodeEncodeError with BeautifulSoup 3.1.0.1 and Python 2.5.2BeautifulSoup 3.1.0.1 和 Python 2.5.2 的 UnicodeEncodeError
【发布时间】:2010-10-02 13:40:04
【问题描述】:

使用 BeautifulSoup 3.1.0.1 和 Python 2.5.2,并尝试解析法语网页。但是,一旦我调用 findAll,我就会收到以下错误:

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

下面是我目前正在运行的代码:

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("http://fr.encarta.msn.com/encyclopedia_761561798/Paris.html")
soup = BeautifulSoup(page, fromEncoding="latin1")
r = soup.findAll("table")
print r

有人知道为什么吗?

谢谢!

更新:根据要求,以下是完整的 Traceback

Traceback (most recent call last):
  File "[...]\test.py", line 6, in <module>
    print r
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1146-1147: ordinal not in range(128)

【问题讨论】:

    标签: python encoding screen-scraping beautifulsoup


    【解决方案1】:

    这是另一个想法。您的终端无法显示来自 Python 的 unicode 字符串。解释器首先尝试将其转换为 ASCII。您应该在打印之前对其进行显式编码。我不知道soup.findAll() 的确切语义。但它可能是这样的:

    for t in  soup.findAll("table"):
        print t.encode('latin1')
    

    如果t 真的是一个字符串。也许它只是另一个对象,您必须从中构建要显示的数据。

    【讨论】:

    • 有效! :D 但是“您的终端无法显示来自 Python 的 unicode 字符串”是什么意思。我在 IDLE (Python Shell) 中运行我的脚本。这应该可行,不是吗?
    • 终端必须告诉 Python 解释器它使用什么字符集。通常这是通过环境变量完成的。不知道 IDLE 是怎么处理的。
    • 打印 repr(t) 也很有用。将您输出的用于调试目的的 repr() 内容通常是一个好主意,这样您就可以准确地看到其中潜伏的类型和任何最高位集或控制字符,并且不会使您的调试代码抛出更多虚假异常.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多