Python自動檢測requests所獲得html文檔的編碼
使用chardet庫自動檢測requests所獲得html文檔的編碼
使用requests和BeautifulSoup庫獲取某個頁面帶來的亂碼問題
使用requests配合BeautifulSoup庫,可以輕松地從網(wǎng)頁中提取數(shù)據(jù)。但是,當網(wǎng)頁返回的編碼格式與Python默認的編碼格式不一致時,就會導(dǎo)致亂碼問題。
以如下代碼為例,它會獲取到一段亂碼的html:
import requests
from bs4 import BeautifulSoup
# 目標 URL
url = 'https://finance.sina.com.cn/realstock/company/sh600050/nc.shtml'
# 發(fā)送 HTTP GET 請求
response = requests.get(url)
# 檢查請求是否成功
if response.status_code == 200:
# 獲取網(wǎng)頁內(nèi)容
html_content = response.text
# 使用 BeautifulSoup 解析 HTML 內(nèi)容
soup = BeautifulSoup(html_content, 'html.parser')
# 要查找的 ID
target_id = 'hqDetails'
# 查找具有特定 ID 的標簽
element = soup.find(id=target_id)
if element:
# 獲取該標簽下的 HTML 內(nèi)容
element_html = str(element)
print(f"ID 為 {target_id} 的 HTML 內(nèi)容:\n{element_html}\n")
# 查找該標簽下的所有 table 元素
tables = element.find_all('table')
if tables:
for i, table in enumerate(tables):
print(f"第 {i+1} 個 table 的 HTML 內(nèi)容:\n{table}\n")
else:
print(f"ID 為 {target_id} 的標簽下沒有 table 元素")
else:
print(f"未找到 ID 為 {target_id} 的標簽")
else:
print(f"請求失敗,狀態(tài)碼: {response.status_code}")

我們可以通過通過手工指定代碼的方式來解決這個問題,例如在response.status_code == 200后,通過response.encoding = 'utf-8'指定代碼,又或通過soup = BeautifulSoup(html_content, 'html.parser', from_encoding='utf-8') 來指定編碼。
然而,當我們獲取的html頁面編碼不確定的時候,有沒有更好的辦法讓編碼監(jiān)測自動執(zhí)行呢?這時候chardet編碼監(jiān)測庫是一個很好的幫手。
使用 chardet 庫自動檢測編碼
chardet 是一個用于自動檢測字符編碼的庫,可以更準確地檢測響應(yīng)的編碼。
安裝chardet庫
pip install chardet
代碼應(yīng)用示例
import requests
from bs4 import BeautifulSoup
import chardet
# 目標 URL
url = 'https://finance.sina.com.cn/realstock/company/sh600050/nc.shtml'
# 發(fā)送 HTTP GET 請求
response = requests.get(url)
# 檢查請求是否成功
if response.status_code == 200:
# 自動檢測字符編碼
detected_encoding = chardet.detect(response.content)['encoding']
# 設(shè)置響應(yīng)的編碼
response.encoding = detected_encoding
# 獲取網(wǎng)頁內(nèi)容
html_content = response.text
# 使用 BeautifulSoup 解析 HTML 內(nèi)容
soup = BeautifulSoup(html_content, 'html.parser')
# 要查找的 ID
target_id = 'hqDetails'
# 查找具有特定 ID 的標簽
element = soup.find(id=target_id)
if element:
# 獲取該標簽下的 HTML 內(nèi)容
element_html = str(element)
print(f"ID 為 {target_id} 的 HTML 內(nèi)容:\n{element_html}\n")
# 查找該標簽下的所有 table 元素
tables = element.find_all('table')
if tables:
for i, table in enumerate(tables):
print(f"第 {i+1} 個 table 的 HTML 內(nèi)容:\n{table}\n")
else:
print(f"ID 為 {target_id} 的標簽下沒有 table 元素")
else:
print(f"未找到 ID 為 {target_id} 的標簽")
else:
print(f"請求失敗,狀態(tài)碼: {response.status_code}")

可見,通過使用chardet庫,可以有效實現(xiàn)代碼的自動檢測。
以上就是Python自動檢測requests所獲得html文檔的編碼的詳細內(nèi)容,更多關(guān)于Python檢測requests獲得html文檔編碼的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用python實現(xiàn)strcmp函數(shù)功能示例
這篇文章主要介紹了使用python實現(xiàn)strcmp函數(shù)功能的示例,需要的朋友可以參考下2014-03-03
教你Pycharm安裝使用requests第三方庫的詳細教程
PyCharm安裝第三方庫是十分方便的,無需pip或其他工具,平臺就自帶了這個功能而且操作十分簡便,今天通過本文帶領(lǐng)大家學(xué)習(xí)Pycharm安裝使用requests第三方庫的詳細教程,感興趣的朋友一起看看吧2021-07-07

