簡體   English   中英

UnicodeEncodeError:'ascii'編解碼器無法編碼字符u'\\ u2026'

[英]UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026'

我正在學習urllib2和Beautiful Soup,並且在第一次測試時遇到如下錯誤:

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

關於這種類型的錯誤似乎有很多帖子,我已經嘗試了我能理解的解決方案,但似乎有22個跟他們一起,例如:

我想打印post.text (文本是一個美麗的湯方法,只返回文本)。 str(post.text)post.text產生unicode錯誤(在右撇號的'... )。

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

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 = post.encode("utf-8") (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)

為了嘗試可能有用的東西,我從這里安裝了lxml for Windows並使用以下方法實現:

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 2中,只有在可以轉換為ASCII的情況下才能打印unicode對象。 如果無法用ASCII編碼,您將收到該錯誤。 您可能希望對其進行顯式編碼,然后打印生成的str

print post.text.encode('utf-8')
    html = urllib.request.urlopen(THE_URL).read()
    soup = BeautifulSoup(html)
    print("'" + str(soup.encode("ascii")) + "'")

為我工作;-)

你試過.decode().decode("utf-8")嗎?

並且,我建議使用html5lib parser使用lxml

http://lxml.de/html5parser.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM