2 回答

TA貢獻(xiàn)1848條經(jīng)驗 獲得超10個贊
您不想忽略這些字符。它們表示您收到的數(shù)據(jù)已使用錯誤的字符編碼進(jìn)行解碼。在您的情況下requests,錯誤地猜測編碼是latin-1. 真正的編碼是在 HTML 響應(yīng)utf-8的<meta>標(biāo)簽中指定的。requests是一個用于處理 HTTP 的庫,它不了解 HTML。由于Content-Type標(biāo)頭未指定編碼,因此requests只能猜測編碼。BeautifulSoup但是,它是一個用于處理 HTML 的庫,它非常擅長檢測編碼。因此,您希望從響應(yīng)中獲取原始字節(jié)并將其傳遞給BeautifulSoup. IE。
from bs4 import BeautifulSoup
import requests
response = requests.get("https://mattgemmell.com/network-link-conditioner-in-lion/")
data = response.content # we now get `content` rather than `text`
assert type(data) is bytes
soup = BeautifulSoup(data, 'lxml')
article = soup.find_all('article')[0]
text = article.find_all('p')[1].text
print(text)
assert type(text) is str
assert 'Mac OS X 10.7 “Lion”' in text

TA貢獻(xiàn)1818條經(jīng)驗 獲得超7個贊
使用第三個參數(shù)來bytes告訴它如何處理錯誤:
converted_text = bytes(text, 'latin-1', 'ignore')
^^^^^^
你會丟失箭頭,但其他一切都完好無損:
>>> text = '\n← Find Patterns in text on Lion\nUsing Spaces on OS X Lion →\n'
>>> converted_text = bytes(text, 'latin-1', 'ignore')
>>> converted_text
'\n Find Patterns in text on Lion\nUsing Spaces on OS X Lion \n'
以下是有關(guān)文檔中參數(shù)的更多信息 - https://docs.python.org/3.3/howto/unicode.html:
errors 參數(shù)指定無法根據(jù)編碼規(guī)則轉(zhuǎn)換輸入字符串時的響應(yīng)。此參數(shù)的合法值為“strict”(引發(fā) UnicodeDecodeError 異常)、“replace”(使用 U+FFFD、REPLACEMENT CHARACTER)或“ignore”(僅將字符排除在 Unicode 結(jié)果之外)。
添加回答
舉報