我這里有以下代碼:
import aiohttp
import asyncio
from bs4 import BeautifulSoup
async def main():
async with aiohttp.ClientSession() as session:
async with session.get('https://www.pro-football-reference.com/years/2021/defense.htm') as response:
soup = BeautifulSoup(await response.text(), features="lxml")
print(soup)
asyncio.run(main())
但是,它給了我UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdf in position 2170985: invalid continuation byte該行的錯誤await response.text()。我認為問題在于 url 以 a.htm而不是 a結尾.com。
有什么辦法可以解碼嗎?
注意:我不想使用 response.read()。
uj5u.com熱心網友回復:
該網站的標題表明該頁面應編碼為 UTF-8,但顯然不是:
$ curl --head --silent https://www.pro-football-reference.com/years/2021/defense.htm | grep -i charset
content-type: text/html; charset=UTF-8
讓我們檢查一下內容:
>>> r = requests.get('https://www.pro-football-reference.com/years/2021/defense.htm')
>>> r.content[2170980:2170990]
b'/">Fu\xdfball'
看起來這應該是“Fu?ball”,b'Fu\xc3\x9fball'如果用 UTF-8 編碼就是這樣。
如果我們仰望0xdf在傳統的8位編碼的Triplee的表,我們發現,它代表了這些編碼的“SS”:
cp1250, cp1252, cp1254, cp1257, cp1258, iso8859_10, iso8859_13, iso8859_14, iso8859_15, iso8859_16, iso8859_2, iso8859_3, iso8859_3, laos1,
在沒有任何其他資訊的情況下,我會選擇 latin-1 作為編碼;然而,傳遞request.content給 Beautiful Soup 并讓它處理解碼可能更簡單。
uj5u.com熱心網友回復:
好奇為什么不在pandas這里使用?
import pandas as pd
url = 'https://www.pro-football-reference.com/years/2021/defense.htm'
df = pd.read_html('https://www.pro-football-reference.com/years/2021/defense.htm', header=1)[0]
df = df[df['Rk'].ne('Rk')]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/374101.html
