重定向延遲:這個時間在 301 到 200 之間,或者兩次重定向之間的時間可能是 301。
就像一個 Chrome 擴展:

如何使用請求庫測量重定向延遲?
import requests
r = 'http://httpbin.org/redirect/3'
r = requests.head(r, allow_redirects=True, stream=True)
r.elapsed
r.elapsed不是我需要的,它顯示了發送請求和它收到的第一個內容之間的時間。
uj5u.com熱心網友回復:
選項1
使用該requests庫,您必須將allow_redirects引數設定為False并有一個回圈,您可以在其中查找Location回應標頭(指示要將頁面重定向到的 URL),然后對該 URL 執行新請求,最后測量總經過的時間。
但是,您可能會發現使用httpx庫更容易做到這一點,它與 Python 非常相似requests,但具有更多功能。您可以將follow_redirects引數設定為False(無論如何都是默認值)并使用物件.next_request的Response屬性將重定向 URL 獲取到已構建的Request物件中。如前所述,您可以有一個回圈來分別發送每個請求并測量它們的回應時間(= 傳輸延遲 處理時間)。response.elapsed回傳一個物件,其中timedelta包含從發送請求到回應到達所經過的時間。通過將所有回應時間相加,您可以測量已用的總時間。例子:
import httpx
import time
url = 'http://httpbin.org/redirect/3'
with httpx.Client() as client:
r = client.get(url, follow_redirects=False)
print(r.url, r.elapsed, '', sep='\n')
total = r.elapsed.total_seconds()
while 300 < r.status_code < 400:
r = client.send(r.next_request)
print(r.url, r.elapsed, '', sep='\n')
total = r.elapsed.total_seconds()
print(f'Total time elapsed: {total} s')
選項 2
將follow_redirects引數設定為True并使用物件的.history屬性Response來獲取導致最終 URL 的回應串列。該.history屬性包含遵循的所有重定向回應的串列,按照它們的生成順序。您可以測量每個請求的經過時間以及總經過時間,如上面的選項 1 所示。例子:
import httpx
import time
url = 'http://httpbin.org/redirect/3'
with httpx.Client() as client:
r = client.get(url, follow_redirects=True)
if r.history:
total = 0
for resp in r.history:
print(resp.url, resp.elapsed, '', sep='\n')
total = resp.elapsed.total_seconds()
print(r.url, r.elapsed, '', sep='\n')
total = r.elapsed.total_seconds()
print(f'Total time elapsed: {total} s')
在 Python requests(而不是httpx)中,上述方法如下:
import requests
url = 'http://httpbin.org/redirect/3'
r = requests.get(url, allow_redirects=True)
if r.history:
total = 0
for resp in r.history:
print(resp.url, resp.elapsed, '', sep='\n')
total = resp.elapsed.total_seconds()
print(r.url, r.elapsed, '', sep='\n')
total = r.elapsed.total_seconds()
print(f'Total time elapsed: {total} s')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/511815.html
上一篇:物體之間的碰撞?
