美丽的汤统一code EN code错误 [英] Beautiful Soup Unicode encode error
本文介绍了美丽的汤统一code EN code错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想下面的code与特定的HTML文件
I am trying the following code with a particular HTML file
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')
我收到以下错误:
I get the following error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 9: ordinal not in range(128)
如何调试呢?
当我删除调用打印功能我没有得到任何错误。
I do not get any error when I remove the call to print function.
推荐答案
STR(段)
内置尝试使用默认值( ASCII
)编码的UNI code在对
。
这是的连接code()
调用之前完成的
The str(para)
builtin is trying to use the default (ascii
) encoding for the unicode in para
.
This is done before the encode()
call:
>>> 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'
>>>
尝试编码对
直接,也许通过应用连接code(UTF-8)
来每个列表元素。
Try encoding para
directly, maybe by applying encode("utf-8")
to each list element.
这篇关于美丽的汤统一code EN code错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文