小编Pek*_*nen的帖子

漂亮的汤和字符编码

我正在尝试使用Beautiful Soup和Python 2.6.5从具有斯堪的纳维亚字符的网站中提取文本和HTML。

html = open('page.html', 'r').read()
soup = BeautifulSoup(html)

descriptions = soup.findAll(attrs={'class' : 'description' })

for i in descriptions:
    description_html = i.a.__str__()
    description_text = i.a.text.__str__()
    description_html = description_html.replace("/subdir/", "http://www.domain.com/subdir/")
    print description_html
Run Code Online (Sandbox Code Playgroud)

但是,执行后,程序将失败,并显示以下错误消息:

Traceback (most recent call last):
    File "test01.py", line 40, in <module>
        description_text = i.a.text.__str__()
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 19:         ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

如果有帮助的话,输入页面似乎采用ISO-8859-1编码。我尝试使用设置正确的源编码,BeautifulSoup(html, fromEncoding="latin-1")但也无济于事。

现在是2011年,我正在努力解决一些琐碎的字符编码问题,我相信所有这一切都有一个非常简单的解决方案。

html python encoding python-2.x

4
推荐指数
1
解决办法
2472
查看次数

标签 统计

encoding ×1

html ×1

python ×1

python-2.x ×1