python - Beautiful Soup 和字符编码

标签 python html encoding python-2.x

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

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

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)

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

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

最佳答案

i.a.__str__('latin-1')

i.a.text.encode('latin-1')

应该可以。

你确定是 latin-1 吗?它应该正确检测编码。

此外,如果不需要指定编码,为什么不直接使用 str(i.a)

编辑:看起来你需要 install chardet使其自动检测编码。

关于python - Beautiful Soup 和字符编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7050044/

相关文章:

python - Python 3 的 UTF-8 编码问题

php - 在 PHP 服务器上启用 GZIP?

PHP自编码算法

python - Matplotlib 中的一半或四分之一极 map ?

python - 在Python中使用Unix命令(在我的例子中是node.js/lessc)?

python - 模块对象没有属性 'Screen'

html - 使用 CSS 缩放整个 HTML 元素

python - 带有十六进制输入的 Python 中的 CRC32 校验和

javascript - 如何将我的网页翻译成其他语言?

javascript - 使用行跨度在表格中垂直获取下一个表格单元格