我正在学习urllib2和Beautiful Soup,但在第一次测试时出现了错误,例如:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 10: ordinal not in range(128)
似乎有很多关于这种错误的帖子,我已经尝试了我能理解的解决方案,但它们似乎存在一些困难,例如:
我想打印post.text
(其中text是一个返回文本的beautiful soup方法)。
str(post.text)
和post.text
会产生unicode错误(在像右撇号'
和...
这样的字符上)。
因此,在str(post.text)
上面添加post = unicode(post)
,然后我得到:
AttributeError: 'unicode' object has no attribute 'text'
我也尝试了
(post.text).encode()
和(post.text).renderContents()
。后者产生了错误:AttributeError: 'unicode' object has no attribute 'renderContents'
然后我尝试使用str(post.text).renderContents()
,但出现了错误:
AttributeError: 'str' object has no attribute 'renderContents'
如果我可以在文档顶部定义'使这个内容可解释'
,并且仍然可以访问所需的text
函数,那就太好了。
更新: 经过建议:
如果我在str(post.text)
之前添加post = post.decode("utf-8")
,我会得到:
TypeError: unsupported operand type(s) for -: 'str' and 'int'
如果我在
str(post.text)
上面添加 post = post.decode()
,那么我会得到:AttributeError: 'unicode' object has no attribute 'text'
如果我在
(post.text)
上方添加 post = post.encode("utf-8")
,那么我会得到以下结果:AttributeError: 'str' object has no attribute 'text'
我尝试了
print post.text.encode('utf-8')
并得到了以下结果:UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 39: ordinal not in range(128)
为了尝试可能有效的事情,我从这里安装了适用于Windows的lxml,并通过以下方式实现:
parsed_content = BeautifulSoup(original_content, "lxml")
根据http://www.crummy.com/software/BeautifulSoup/bs4/doc/#output-formatters的介绍,这些步骤似乎没有什么区别。 我正在使用Python 2.7.4和Beautiful Soup 4。
解决方案:
深入了解unicode、utf-8和Beautiful Soup类型后,发现与我的打印方法有关。我删除了所有的
str
方法和连接操作,例如str(something) + post.text + str(something_else)
,改为something, post.text, something_else
,看起来打印效果很好,但在这个阶段我对格式控制的能力较弱(例如在,
处插入空格)。