Request庫使用response.text返回亂碼問題


我們日常使用Request庫獲取response.text,這種調用方式返回的text通常會有亂碼顯示:

import requests

res = requests.get("https://www.baidu.com")
print(res.text)

#...name=tj_briicon class="bri" style="display: block;">更多产品</a> </div> </di...

 

如上:出現了亂碼

解決方案:一

import requests

res = requests.get("https://www.baidu.com")
print(res.content.decode('utf-8'))

#...name=tj_briicon class="bri" style="display: block;">更多產品</a> </div> ...

  

如上:使用這種方法調用顯示了正確的中文

  使用res.content時,返回的數據格式其實是二進制格式,然后通過decode()轉換為utf-8,這樣就解決了通過response.text直接返回顯示亂碼的問題

 

解決方案:二

import requests

res = requests.get("https://www.baidu.com")
res.encoding = 'utf-8'
print(res.text)
#...name=tj_briicon class=bri style="display: block;">更多產品</a> </div> </d...

Requests 會基於 HTTP 頭部對響應的編碼作出有根據的推測。當你訪問 response.text 之時,Requests 會使用其推測的文本編碼。你可以找出 Requests 使用了什么編碼,並且能夠使用 response.encoding 屬性來改變它


免責聲明!

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



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