基于Python中request請求得到的response的屬性問題
Python中request請求得到的response,即通過request得到的數(shù)據(jù):
import requestsresponse = requests.get(https://www.jd.com/)response 的屬性1、返回狀態(tài)碼
response.status_code
http請求的返回狀態(tài),2XX 表示連接成功,3XX 表示跳轉(zhuǎn) ,4XX 客戶端錯誤 , 500 服務器錯誤
2、返回http響應的文本內(nèi)容response.text
http響應內(nèi)容的字符串(str)形式,請求url對應的頁面內(nèi)容
response=requests.get('https://www.jd.com/')print(response.text)
如果打印的過程中出現(xiàn)亂碼:
則可以使用encoding來修改編碼格式:
response.encoding='utf-8'print(response.text)
3、返回http響應的二進制數(shù)據(jù)
response =requests.get('https://www.jd.com/')# print(response.content) #打印出的是二進制形式print(response.content.decode('utf-8'))
總結(jié):
response的text方法和response的content方法進行對比:
response.text返回的是Unicode型數(shù)據(jù),response.content返回的是bytes型,也就是二進制類型的數(shù)據(jù);
取文本用.text的方法,取圖片用.content的方法;
4、從HTTP header中猜測的響應內(nèi)容編碼方式response.encoding5、從內(nèi)容分析出的響應內(nèi)容的編碼方式(備選編碼方式)
response.apparent_encoding6、http響應內(nèi)容的頭部內(nèi)容
response.headers
補充:python 爬蟲 requests模塊(response常用屬性)
response常用屬性content獲取的response對象中的二進制(byte)類型的頁面數(shù)據(jù)
response.content
返回響應狀態(tài)碼
response.status_code
200
返回響應頭信息
response.headers
獲取請求url
response.url
https://www.sogou.com/
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
