requests庫之response響應對象API詳解


前言

requests庫請求通常用於從特定資源URI中獲取響應內容。

每當我們通過Python向指定URI發出請求時,它都會返回一個響應對象。此時此響應對象用於訪問某些功能,例如內容,標頭等。

response.json()【Requests中內置的JSON解碼器】

①如果接口響應體的格式是json格式時,可以使用 response.json() 獲取接口響應值的python字典數據類型【相當於將接口返回的json字符串格式的響應體通過python的反序列化轉為python字典格式】

注意與postman接口請求工具中的響應結果區分:

②postman工具中請求后的接口響應體是json字符串格式。【與response.json()區分】【可以通過python的反序列化將json字符串轉為與r.json()數據類型相同的python字典格式

通常,在接口自動化中,需要將接口的響應的json字符串響應體轉為python字典格式【因為不論從Excel或者從Yaml讀取的用例都是json字符串格式(與postman中的接口響應值相同)】,然后通過字典方式取值;與response.json()中某個字段值斷言。

③注意 response.json() (返回的響應體數據類型為python字典)和 response.text (返回的響應體數據類型為python字符串【會自動根據響應頭部的字符編碼進行解碼】)返回接口響應內容兩者的區別:

response.ok

如果status_code小於200,response.ok返回True。

如果status_code大於200,response.ok返回False。

例如:

①token未過期: response.ok 返回Ture

②token已過期: response.ok 返回False

response.url

response.url返回請求和響應的URL。【如果GET請求方法的URL中的查詢參數中包含中文,則返回中文被編碼后的URL

完成所有重定向后,它將顯示返回內容的主URL。

response.raw

 response.raw 返回請求后得到此響應對象的原始響應體對象。【 urllib 的response響應對象,可以使用 response.raw.read() 讀取】

response.request.body

 response.request.body 返回此響應的請求對象中的請求體數據。【如果POST請求方法的請求體中包含中文內容,則返回中文被編碼后的請求體

【注意】:GET請求得到的response對象中的請求對象的請求體request body為None。

response.request.headers

 response.request.headers 返回此響應的請求對象中的請求頭數據字典。

response.request

 response.request返回請求此響應的請求對象。

response.reason

 response.reason返回與響應狀態碼相對應的描述文本

例如:“確定”為200;“未找到”為404。

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://api.github.com/') 
  
# print response 
print(response) 
  
# print the reason 
print(response.reason) 
  
# ping an incorrect url 
response = requests.get('https://geeksforgeeks.org / naveen/') 
  
# print response 
print(response) 
  
# print the reason now 
print(response.reason)

運行結果:

response.encoding

response.encoding 返回用於解碼 response.content 的編碼方式。【或者理解為將響應內容編碼為二進制的編碼方式】

response.encoding 是response headers響應頭 Content-Type 字段 charset 的值。【 瀏覽器/postman等接口請求工具將會自動使用該編碼方式解碼服務端響應的內容】

response.encoding 是從http協議中的response headers響應頭中的charset字段中提取的編碼方式;

若response headers響應頭中沒有charset字段,則服務器響應的內容默認為 ISO-8859-1 編碼模式【使用此編碼方式無法解析中文內容,會造成響應體亂碼(解析為亂碼數據)】

response.apparent_encoding

response.apparent_encoding 會自動的從服務器接口響應的內容中(響應體)分析內容編碼的方式,所以 apparent_encoding 比 encoding 更加准確。當網頁或者接口響應內容出現亂碼時可以把 apparent_encoding 的編碼格式賦值給encoding。

response.content

response.content 以字節為單位返回接口響應的內容。本質上,它是指二進制響應內容。【會自動解碼 gzip 和 deflate 壓縮】

比如接口的響應是一張圖片,我們就需要讀取響應體的二進制數據並在本地存為一個圖片。

在輸出開始時檢查 b’,它表示對字節對象的引用。【即表示輸出的內容為字節對象】

response.links

response.links 返回標題鏈接。

檢查輸出開始處的{},它是否顯示標題鏈接JSON。

response.headers

 response.headers 返回響應頭即response headers的數據字典。【該字典的字典鍵不區分大小寫,若鍵不存在則返回None】

response.request.headers

 response.request.headers 返回請求頭即request headers的數據字典。

response.history

response.history 返回包含請求(URL)歷史的響應對象列表。

本質上,它以響應列表的形式顯示請求如何到達目標。【比如重定向】

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://geeksforgeeks.org') 
  
# print response 
print(response) 
  
# print history 
print(response.history)

運行結果:

response.elapsed

response.elapsed返回一個timedelta對象,其中包含從發送請求到響應到達所經過的時間。它通常用於在某個時間點“elapsed”之后停止連接。

response.raise_for_status()

如果在處理過程中發生錯誤,則 response.raise_for_status()返回 HTTPError 對象。它用於調試請求模塊,並且是Python請求的組成部分。

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://api.github.com/') 
  
# print response 
print(response) 
  
# print check if an error has occurred 
print(response.raise_for_status()) 
  
# ping an incorrect url 
response = requests.get('https://geeksforgeeks.org / naveen/') 
  
# print check if an error has occurred 
print(response.raise_for_status())

運行結果:

檢查Traceback錯誤,它表明已發生錯誤以及錯誤“Invalid URL”和狀態代碼404。

response.iter_content()

response.iter_content()遍歷response.content。 

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://geeksforgeeks.org') 
  
# print response 
print(response) 
  
# print iter_content data 
print(response.iter_content()) 
  
# iterates over the list 
for i in response.iter_content():
    print(i)

運行結果:

檢查輸出開始處的迭代器對象和迭代器,它分別以字節為單位顯示迭代器對象和迭代元素。

response.is_permanent_redirect

如果響應是永久重定向的URL,則 response.is_permanent_redirect 返回True,否則返回False。

301重定向是從一個URL到另一個URL的永久重定向。

301將發送的網站訪問者和搜索引擎重定向到與他們最初在瀏覽器中鍵入或從搜索引擎結果頁面選擇的URL不同的URL。

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://geeksforgeeks.org') 
  
# print response 
print(response) 
  
# print is_permanent_redirect flag 
print(response.is_permanent_redirect)

運行結果:

response.is_redirect

如果響應已重定向,則 response.is_redirect 返回True,否則返回False。

# import requests module 
import requests 
  
# Making a get request 
response = requests.get('https://geeksforgeeks.org') 
  
# print response 
print(response) 
  
# print is_redirect Flag 
print(response.is_redirect)

運行結果:

response.close()

close()來自響應對象。 response.close() 表示關閉與服務器的連接。

# import requests module 
import requests 
  
# Making a put request 
response = requests.get('https://api.github.com') 
  
# print response 
print(response) 
  
# closing the connection 
response.close() 
  
# Check if this gets execeuted 
print("Connection Closed")

運行結果:

response.request.hooks

requests提供了hook機制,讓我們能夠在請求得到響應之后去做一些自定義的操作;比如打印某些信息、修改響應內容等。

舉例:

import requests


# 鈎子函數1
def print_url(r, *args, **kwargs):
    print("raw_url " + r.url)


# 鈎子函數2
def change_url(r, *args, **kwargs):
    r.url = 'http://change.url'
    print("changed_url " + r.url)
    return r  # 其實沒有這句話,也可以修改r.url,因為r是response對象而非普通數值,但requests官方似乎誤認為回調函數一定要有return才能替換傳入的數據


# tips: http://httpbin.org能夠用於測試http請求和響應
url = 'http://httpbin.org/cookies'
response = requests.get(url, hooks=dict(response=[print_url, change_url]))
print("result_url " + response.url)

運行結果:

解釋:

在上述例子中:

①定義了兩個鈎子函數,分別用來打印response對象中的url(print_url)和修改response對象中的url(change_url)。

②通過參數 hooks=dict(response=[print_url, change_url])調用。其中response是鈎子的類型

③從運行結果中,可以看出鈎子函數1(print_url)和鈎子函數2(change_url)被順序執行了,且達到了篡改響應結果的目的。

④在上述例子中,只在requests方法級別調用了一次hook,如果想要每個請求都使用hook呢?可以在requests的session對象中添加hook來讓該session對象發出去的請求均帶有hook,例如:

s = requests.Session()

s.hooks.update({"response": [print_url, change_url]})

 


免責聲明!

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



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