UnicodeEncodeError:'ascii'编解码器不能编码字符u'\ u2026'

use*_*287 28 python unicode urllib2 beautifulsoup python-2.7

我正在学习urllib2和Beautiful Soup,并且在第一次测试时遇到如下错误:

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 10: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

关于这种类型的错误似乎有很多帖子,我已经尝试了我能理解的解决方案,但似乎有22个跟他们一起,例如:

我想打印post.text(文本是一个美丽的汤方法,只返回文本). str(post.text)post.text产生unicode错误(如右撇号'...).

所以我在post = unicode(post)上面添加str(post.text),然后我得到:

AttributeError: 'unicode' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)

我也试过(post.text).encode()(post.text).renderContents().后者产生错误:

AttributeError: 'unicode' object has no attribute 'renderContents'
Run Code Online (Sandbox Code Playgroud)

然后我尝试str(post.text).renderContents()并得到错误:

AttributeError: 'str' object has no attribute 'renderContents'
Run Code Online (Sandbox Code Playgroud)

如果我可以在文档的顶部定义某个位置'make this content 'interpretable''并仍然可以访问所需的text功能,那将是很棒的.


更新: 建议后:

如果我在post = post.decode("utf-8")上面添加,str(post.text)我得到:

TypeError: unsupported operand type(s) for -: 'str' and 'int'  
Run Code Online (Sandbox Code Playgroud)

如果我在post = post.decode()上面添加,str(post.text)我得到:

AttributeError: 'unicode' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)

如果我在post = post.encode("utf-8")上面添加,(post.text)我得到:

AttributeError: 'str' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)

我试过print post.text.encode('utf-8')了:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 39: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

为了尝试可能有用的东西,我从这里安装了lxml for Windows 并使用以下方法实现:

parsed_content = BeautifulSoup(original_content, "lxml")
Run Code Online (Sandbox Code Playgroud)

根据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它似乎打印得很好,除了我在这个阶段对格式的控制较少(例如插入空格,).

ick*_*fay 45

在Python 2中,unicode只有在可以将对象转换为ASCII时才能打印对象.如果无法用ASCII编码,您将收到该错误.您可能希望对其进行显式编码,然后打印结果str:

print post.text.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)

  • @ user1063287:基本上,Python 2发生了这种奇怪的`str`和`unicode`事件。如果将它们串联起来,它将隐式编码或解码(我忘记了)为ASCII,以便它们是同一类型。当然,当您处理非ASCII内容时,您不能这样做:您必须*明确*确保所有内容都是同一类型。Python 3解决了这个问题,方法是在混合使用它们时引发错误,而不是求助于有时无法正常工作的行为。 (2认同)