![](/img/trans.png)
[英]I keep getting UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 1: invalid start byte
[英]UnicodeDecodeError 'utf-8' codec can't decode byte 0x92 in position 2893: invalid start byte
我正在嘗試打開一系列HTML文件,以便使用BeautifulSoup從這些文件的主體中獲取文本。 我有大約435個文件要運行,但是一直出現此錯誤。
我試過將HTML文件轉換為文本並打開文本文件,但遇到相同的錯誤...
path = "./Bitcoin"
for file in os.listdir(path):
with open(os.path.join(path, file), "r") as fname:
txt = fname.read()
我想獲取HTML文件的源代碼,以便可以使用beautifulsoup解析它,但出現此錯誤
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-133-f32d00599677> in <module>
3 for file in os.listdir(path):
4 with open(os.path.join(path, file), "r") as fname:
----> 5 txt = fname.read()
~/anaconda3/lib/python3.7/codecs.py in decode(self, input, final)
320 # decode input (taking the buffer into account)
321 data = self.buffer + input
--> 322 (result, consumed) = self._buffer_decode(data, self.errors, final)
323 # keep undecoded input until the next call
324 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x92 in position 2893: invalid start byte
有多種方法可以處理編碼未知的文本數據。 但是,在這種情況下,因為您打算將數據傳遞給Beautiful Soup,所以解決方案很簡單:不要費心嘗試自己解碼文件,讓Beautiful Soup來做。 Beautiful Soup會自動將字節解碼為unicode 。
在當前代碼中,您以文本模式讀取文件,這意味着Python會假定該文件已編碼為UTF-8,除非您為open
函數提供了編碼參數。 如果文件內容無效的UTF-8,則會導致錯誤。
for file in os.listdir(path):
with open(os.path.join(path, file), "r") as fname:
txt = fname.read()
而是以二進制模式讀取html文件,並將生成的bytes
實例傳遞給Beautiful Soup。
for file in os.listdir(path):
with open(os.path.join(path, file), "rb") as fname:
bytes_ = fname.read()
soup = BeautifulSoup(bytes_)
FWIW,當前引起問題的文件可能使用cp1252或類似的Windows 8位編碼進行編碼。
>>> '’'.encode('cp1252')
b'\x92'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.