【发布时间】:2013-04-21 12:40:47
【问题描述】:
我正在学习 urllib2 和 Beautiful Soup,在第一次测试中遇到如下错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' in position 10: ordinal not in range(128)
似乎有很多关于此类错误的帖子,我已经尝试了我能理解的解决方案,但似乎有 22 个问题,例如:
我想打印post.text(其中 text 是一个漂亮的汤方法,它只返回文本)。
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'
如果我可以在文档顶部的某个位置定义 'make this content 'interpretable'' 并且仍然可以访问所需的 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)
为了尝试可行的方法,我从here 安装了适用于 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,它似乎打印得很好,除非我在这个阶段对格式的控制较少(例如,在, 处插入空格)。
【问题讨论】:
标签: python python-2.7 unicode beautifulsoup urllib2