python擷取url響應

來源:互聯網
上載者:User

標籤:str   call   between   latest   UI   request   org   很多   imp   

前言

requests發請求時,介面的回應時間,也是我們需要關注的一個點,如果回應時間太長,也是不合理的。
如果服務端沒及時響應,也不能一直等著,可以設定一個timeout逾時的時間

關於requests請求的回應時間,官網上沒太多介紹,並且我百度搜了下,看很多資料寫的是r.elapsed.microseconds擷取的,然而都是錯的!!!

elapsed官方文檔
  1. elapsed方法的官方文檔地址:http://cn.python-requests.org/zh_CN/latest/api.html#requests.Response
requests.Response     elapsed = None     The amount of time elapsed between sending the request and the arrival of the response (as a timedelta). This property specifically measures the time taken between sending the first byte of the request and finishing parsing the headers. It is therefore unaffected by consuming the response content or the value of the stream keyword argument. 簡單翻譯:計算的是從發送請求到服務端響應回來這段時間(也就是時間差),發送第一個資料到收到最後一個資料之間,這個時間長度不受響應的內容影響

2.用help()查看elapsed裡面的方法

import requestsr = requests.get("https://www.baidu.com")help(r.elapsed)

elapsed裡面幾個方法介紹

  • total_seconds 總時間長度,單位秒

  • days 以天為單位

  • microseconds (>= 0 and less than 1 second) 擷取微秒部分,大於0小於1秒

  • seconds Number of seconds (>= 0 and less than 1 day) 秒,大於0小於1天

  • max = datetime.timedelta(999999999, 86399, 999999) 最大時間

  • min = datetime.timedelta(-999999999) 最小時間

  • resolution = datetime.timedelta(0, 0, 1) 最小時間單位

擷取回應時間

1.擷取elapsed不同的傳回值

import requestsr = requests.get("http://www.cnblogs.com/yoyoketang/")print(r.elapsed)print(r.elapsed.total_seconds())print(r.elapsed.microseconds)print(r.elapsed.seconds)print(r.elapsed.days)print(r.elapsed.max)print(r.elapsed.min)print(r.elapsed.resolution)

2.網上很多資料寫的是用microseconds擷取回應時間,再除1000*1000得到時間為秒的單位,當請求小於1s時,發現不出什麼問題。如果時間超過1s,問題就來了。
(很顯然,大於1s的時候,只截取了後面的小數部分)

3.所以擷取回應時間的正確姿勢應該是:r.elapsed.total_seconds(),單位是s

timeout逾時

1.如果一個請求回應時間比較長,不能一直等著,可以設定一個逾時時間,讓它拋出異常

2.如下請求,設定逾時為0.5s,那麼就會拋出這個異常:requests.exceptions.ConnectTimeout: HTTPConnectionPool

import requestsr = requests.get("http://cn.python-requests.org/zh_CN/latest/", timeout=1)print(r.elapsed)print(r.elapsed.total_seconds())print(r.elapsed.microseconds)

  標籤: python介面自動化

python擷取url響應

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.