requests亂碼問題


有三種方法解決請求后亂碼問題。

一:獲取二進制數據,再利用str進行編碼轉換

url='http://music.baidu.com'
r = requests.get(url)
html=r.content
html_doc=str(html,'utf-8') #html_doc=html.decode("utf-8","ignore")
print(html_doc)

二:使用r.text

Requests 會自動解碼來自服務器的內容。大多數 unicode 字符集都能被無縫地解碼。請求發出后,Requests 會基於 HTTP 頭部對響應的編碼作出有根據的推測。當你訪問 r.text 之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,並且能夠使用 r.encoding 屬性來改變它.
但是Requests庫的自身編碼為: r.encoding = ‘ISO-8859-1’
可以 r.encoding 修改編碼

url='http://music.baidu.com'
r=requests.get(url)
r.encoding='utf-8'
print(r.text)

三:apparent_encoding獲取網頁編碼

上面的兩個方法,適用於網頁編碼是utf-8的情況,但如果網頁的默認編碼不是utf-8,那么在設置編碼的話就無從下手的,畢竟編碼的類型那么多。這樣可以使用 apparent_encoding獲取網頁使用的編碼,在進行設置,如下:

import requests

url='http://www.upandashi.com/cjwt/155.html'
r=requests.get(url)
print(r.apparent_encoding)
r.encoding=r.apparent_encoding
print(r.text)

 

 

參考文章:https://www.cnblogs.com/liuliu-word/p/9910197.html

***************不積跬步無以至千里***************


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM