![](/img/trans.png)
[英]UnicodeEncodeError: 'charmap' codec can't encode character
[英]'charmap' codec can't encode character '\xae' While Scraping a Webpage
我正在使用BeautifulSoap
使用Python
進行網絡抓取我收到此錯誤
'charmap' codec can't encode character '\xae' in position 69: character maps to <undefined>
抓取網頁時
這是我的Python
hotel = BeautifulSoup(state.)
print (hotel.select("div.details.cf span.hotel-name a"))
# Tried: print (hotel.select("div.details.cf span.hotel-name a")).encode('utf-8')
當我們嘗試對已編碼的字節字符串進行.encode()
時,通常會在這里遇到此問題。 因此,您可以嘗試先將其解碼為
html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")
舉個例子:
html = '\xae'
encoded_str = html.encode("utf8")
與失敗
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)
而:
html = '\xae'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")
print encoded_str
®
成功無誤。 請注意,我以“ windows-1252” 為例 。 我從chardet那里得到了它,對它的置信度為0.5,這是正確的! (同樣,對於長度為1個字符的字符串,您希望得到什么)您應該將其更改為從.urlopen().read()
返回的字節字符串的編碼,以適用於您檢索的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.