2 回答

TA貢獻1848條經驗 獲得超10個贊
您不想忽略這些字符。它們表示您收到的數據已使用錯誤的字符編碼進行解碼。在您的情況下requests,錯誤地猜測編碼是latin-1. 真正的編碼是在 HTML 響應utf-8的<meta>標簽中指定的。requests是一個用于處理 HTTP 的庫,它不了解 HTML。由于Content-Type標頭未指定編碼,因此requests只能猜測編碼。BeautifulSoup但是,它是一個用于處理 HTML 的庫,它非常擅長檢測編碼。因此,您希望從響應中獲取原始字節并將其傳遞給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貢獻1818條經驗 獲得超7個贊
使用第三個參數來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'
以下是有關文檔中參數的更多信息 - https://docs.python.org/3.3/howto/unicode.html:
errors 參數指定無法根據編碼規則轉換輸入字符串時的響應。此參數的合法值為“strict”(引發 UnicodeDecodeError 異常)、“replace”(使用 U+FFFD、REPLACEMENT CHARACTER)或“ignore”(僅將字符排除在 Unicode 結果之外)。
添加回答
舉報