Python request中文亂碼問題解決方案
Python request獲取網(wǎng)頁中文亂碼問題
r = requests.get(“http://www.baidu.com“)
**r.text返回的是Unicode型的數(shù)據(jù)。
使用r.content返回的是bytes型的數(shù)據(jù)。
也就是說,如果你想取文本,可以通過r.text。
如果想取圖片,文件,則可以通過r.content。**
方法1:使用r.text
Requests 會(huì)自動(dòng)解碼來自服務(wù)器的內(nèi)容。大多數(shù) unicode 字符集都能被無縫地解碼。請(qǐng)求發(fā)出后,Requests 會(huì)基于 HTTP 頭部對(duì)響應(yīng)的編碼作出有根據(jù)的推測(cè)。當(dāng)你訪問 r.text 之時(shí),Requests 會(huì)使用其推測(cè)的文本編碼。你可以找出 Requests 使用了什么編碼,并且能夠使用 r.encoding 屬性來改變它.
但是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)文章:
1. Springboot Druid 自定義加密數(shù)據(jù)庫(kù)密碼的幾種方案2. 詳解Android studio 動(dòng)態(tài)fragment的用法3. 解決Android studio xml界面無法預(yù)覽問題4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)5. 什么是python的自省6. Vuex localStorage的具體使用7. php模擬實(shí)現(xiàn)斗地主發(fā)牌8. Spring MVC+ajax進(jìn)行信息驗(yàn)證的方法9. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 使用Android studio查看Kotlin的字節(jié)碼教程

網(wǎng)公網(wǎng)安備