2014-11-23 102 views
36

我想刮一個網站,但它給了我一個錯誤。UnicodeEncodeError:'charmap'編解碼器無法編碼字符

我用下面的代碼:

import urllib.request 
from bs4 import BeautifulSoup 

get = urllib.request.urlopen("https://www.website.com/") 
html = get.read() 

soup = BeautifulSoup(html) 

print(soup) 

而且我發現了以下錯誤:

File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode characters in position 70924-70950: character maps to <undefined> 

我能做些什麼來解決這個問題?

回答

69

我通過將.encode("utf-8")加到soup來修復它。

這意味着print(soup)變爲print(soup.encode("utf-8"))

+1

請勿在您的腳本中硬編碼您的環境的字符編碼(例如,控制檯),[直接打印Unicode](http://stackoverflow.com/a/32176732/4279) – jfs 2015-09-07 04:09:59

+0

這只是打印repr一個'bytes'對象,如果有很多UTF-8編碼的文本,它將打印成'\ x'序列的混亂。正如@ J.F.Sebastian所建議的,我建議使用'win_unicode_console'。 – eryksun 2016-05-23 20:48:01

+0

我使用了上面的解決方案,但sill得到了問題:class MyStreamListener(tweepy.StreamListener): def on_status(self,status): print(str(status.encode(「utf-8」))) UnicodeEncodeError:'charmap '編解碼器不能編碼字符'\ u2019'在位置87:字符映射到 Vivek 2016-09-26 23:49:28

1

對於仍然出現此錯誤的人,將encode("ascii")添加到soup也會解決此問題。

soup = BeautifulSoup(html_doc, 'html.parser').encode("ascii") 
print(soup) 
34

刮保存網頁內容到一個文件時,我得到了相同的UnicodeEncodeError。要解決它,我更換驗證碼:

with open(fname, "w") as f: 
    f.write(html) 

與此:

import io 
with io.open(fname, "w", encoding="utf-8") as f: 
    f.write(html) 

使用io爲您提供向後兼容性與Python 2.如果你只需要支持Python 3中,你可以使用內置open功能代替。

+1

在mac(python 3)完美地工作,只是打開沒有編碼,但在Windows(w10,python3)不是一個選項。只要以這種方式工作,encoding =「utf-8」參數。 – xtornasol512 2017-04-30 01:14:03

+2

謝謝。它爲我工作,我正在處理XML文件,並在新文件中寫入xml.toprettyxml()的結果 – 2018-01-16 17:06:24

相關問題