Python requests亂碼的五種解決辦法
使用requests模塊請求網(wǎng)頁內(nèi)容,經(jīng)常會出現(xiàn)亂碼,例如:
import requests
res = requests.get("https://www.baidu.com/")
print(res.text)

亂碼的原因是內(nèi)容編碼和解碼方式不一致導(dǎo)致的,解決辦法有以下幾種解決辦法:
第一種:apparent_encoding
import requests
res = requests.get("https://www.baidu.com/")
res.encoding = res.apparent_encoding
print(res.text)

第二種:content utf-8解碼
一種臨時性的解決辦法,不建議用這種方法,相當(dāng)于寫死代碼了。
import requests
res = requests.get("https://www.baidu.com/")
try:
txt = res.content.decode('gbk')
except UnicodeDecodeError as e:
# print(e)
txt = res.content.decode('utf-8')
print(txt)

第三種:chardet
import requests
import chardet
res = requests.get("https://www.baidu.com/")
encoding = chardet.detect(res.content)['encoding']
print(res.content.decode(encoding))
第四種:cchardet
cchardet需要提前安裝一下:pip install cchardet。
import requests
import cchardet
res = requests.get("https://www.baidu.com/")
encoding = cchardet.detect(res.content)['encoding']
print(res.content.decode(encoding))
第五種:encode + decode
import requests
import cchardet
res = requests.get("https://www.baidu.com/")
res_encoding = res.encoding # 響應(yīng)的編碼方式
con_encoding = cchardet.detect(res.content)['encoding'] # 內(nèi)容的編碼方式
print(res.text.encode(res_encoding).decode(con_encoding)) # 重新編解碼text
到此這篇關(guān)于Python requests亂碼的五種解決辦法的文章就介紹到這了,更多相關(guān)Python requests亂碼內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
思考分析Python運(yùn)算中?a+=b?和?a=a+b是否相等
這篇文章主要為大家介紹了Python運(yùn)算中a+=b和a=a+b是否相等及原理思考分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
詳解Python小數(shù)據(jù)池和代碼塊緩存機(jī)制
這篇文章主要介紹了詳解Python 小數(shù)據(jù)池和代碼塊緩存機(jī)制的相關(guān)資料,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04
詳解如何用TensorFlow訓(xùn)練和識別/分類自定義圖片
這篇文章主要介紹了詳解如何用TensorFlow訓(xùn)練和識別/分類自定義圖片,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
Pycharm項(xiàng)目代碼同步到Gitee的圖文步驟
本文主要介紹了Pycharm項(xiàng)目代碼同步到Gitee的圖文步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
pycharm 實(shí)現(xiàn)本地寫代碼,服務(wù)器運(yùn)行的操作
這篇文章主要介紹了pycharm 實(shí)現(xiàn)本地寫代碼,服務(wù)器運(yùn)行的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
Django 1.10以上版本 url 配置注意事項(xiàng)詳解
這篇文章主要介紹了Django 1.10以上版本 url 配置注意事項(xiàng)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-08-08

