Pek*_*nen 4 html python 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
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年,我正在努力解决一些琐碎的字符编码问题,我相信所有这一切都有一个非常简单的解决方案。
i.a.__str__('latin-1')
Run Code Online (Sandbox Code Playgroud)
要么
i.a.text.encode('latin-1')
Run Code Online (Sandbox Code Playgroud)
应该管用。
您确定是latin-1吗?它应该正确检测编码。
另外,为什么不使用str(i.a)它,而无需指定编码呢?
编辑:看起来您需要为其安装chardet以自动检测编码。