Python request中文亂碼問題解決方案
Python request獲取網(wǎng)頁(yè)中文亂碼問題
r = requests.get(“http://www.baidu.com“)
**r.text返回的是Unicode型的數(shù)據(jù)。
使用r.content返回的是bytes型的數(shù)據(jù)。
也就是說(shuō),如果你想取文本,可以通過r.text。
如果想取圖片,文件,則可以通過r.content。**
方法1:使用r.text
Requests 會(huì)自動(dòng)解碼來(lái)自服務(wù)器的內(nèi)容。大多數(shù) unicode 字符集都能被無(wú)縫地解碼。請(qǐng)求發(fā)出后,Requests 會(huì)基于 HTTP 頭部對(duì)響應(yīng)的編碼作出有根據(jù)的推測(cè)。當(dāng)你訪問 r.text 之時(shí),Requests 會(huì)使用其推測(cè)的文本編碼。你可以找出 Requests 使用了什么編碼,并且能夠使用 r.encoding 屬性來(lái)改變它.
但是Requests庫(kù)的自身編碼為: r.encoding = ‘ISO-8859-1’
可以 r.encoding 修改編碼
url=’http://music.baidu.com’r=requests.get(url)r.encoding=’utf-8’print(r.text)
方法2:使用r.content
使用r.content,得到的是bytes型,再轉(zhuǎn)為str
url=’http://music.baidu.com’r = requests.get(url)html=r.contenthtml_doc=str(html,’utf-8’) #html_doc=html.decode('utf-8','ignore')print(html_doc)
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
