1. 程式人生 > >Python3 解決中文亂碼 requests庫中文亂碼問題【別的部落格好多都是都是然並卵的教程】

Python3 解決中文亂碼 requests庫中文亂碼問題【別的部落格好多都是都是然並卵的教程】

直接教程

    s=requests.session()
    s.headers['Accept']='text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
    s.headers['Accept-Encoding']='gzip, deflate, br'
    s.headers['Host']='pan.baidu.com'
    s.headers['Accept-Language']='zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7,ko;q=0.6'
    s.headers['User-Agent']='zilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'

    response =s.get(urlsA[0])
    response.encoding = response.apparent_encoding
    data=response.text

教程詳解

 

當使用requests庫的時候,會出現中文亂碼的情況

參考程式碼分析Python requests庫中文編碼問題

      Python HTTP庫requests中文頁面亂碼解決方案!

分析

根據這兩篇文章可知:

    分析requests的原始碼發現,text返回的是處理過的Unicode型的資料,而使用content返回的是bytes型的原始資料。也就是說,r.content相對於r.text來說節省了計算資源,content是把內容bytes返回. 而text是decode成Unicode. 如果headers沒有charset字符集的化,text()會呼叫chardet來計算字符集,這又是消耗cpu的事情.

1

2

3

4

import requests

 

response = requests.get('http://www.dytt8.net/index.htm')

print(response.text[200:300])

這裡測試使用電影天堂的網頁,因為網頁不太標準

輸出為

  

輸出了亂碼

response.encoding

從第二篇文章可以知道reqponse header只指定了type,但是沒有指定編碼(一般現在頁面編碼都直接在html頁面中),查詢原網頁可以看到

再找一個標準點的網頁檢視,比如部落格園的網頁部落格園

response herders的Content-Type指定了編碼型別

《HTTP權威指南》裡第16章國際化裡提到,如果HTTP響應中Content-Type欄位沒有指定charset,則預設頁面是'ISO-8859-1'編碼。這處理英文頁面當然沒有問題,但是中文頁面,就會有亂碼了!

解決

如果在確定使用text,並已經得知該站的字符集編碼時,可以使用 r.encoding = ‘xxx’ 模式, 當你指定編碼後,requests在text時會根據你設定的字符集編碼進行轉換. 

使用apparent_encoding可以獲得真實編碼

1

2

>>> response.apparent_encoding

'GB2312'

這是程式自己分析的,會比較慢

還可以從html的meta中抽取

1

2

>>> requests.utils.get_encodings_from_content(response.text)

['gb2312']

解決方法

1

2

# response.encoding = response.apparent_encoding

response.encoding = 'gb2312'

這時候的輸出為