日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

requests基础3

發布時間:2025/3/21 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 requests基础3 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Cookie

如果某個響應中包含一些 cookie,你可以快速訪問它們:

>>> url = 'http://example.com/some/cookie/setting/url' >>> r = requests.get(url)>>> r.cookies['example_cookie_name'] 'example_cookie_value'

要想發送你的cookies到服務器,可以使用?cookies?參數:

>>> url = 'http://httpbin.org/cookies' >>> cookies = dict(cookies_are='working')>>> r = requests.get(url, cookies=cookies) >>> r.text '{"cookies": {"cookies_are": "working"}}'

Cookie 的返回對象為?RequestsCookieJar,它的行為和字典類似,但界面更為完整,適合跨域名跨路徑使用。你還可以把 Cookie Jar 傳到 Requests 中:

>>> jar = requests.cookies.RequestsCookieJar() >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies') >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere') >>> url = 'http://httpbin.org/cookies' >>> r = requests.get(url, cookies=jar) >>> r.text '{"cookies": {"tasty_cookie": "yum"}}'

重定向與請求歷史

默認情況下,除了 HEAD, Requests 會自動處理所有重定向。

可以使用響應對象的?history?方法來追蹤重定向。

Response.history?是一個?Response?對象的列表,為了完成請求而創建了這些對象。這個對象列表按照從最老到最近的請求進行排序。

例如,Github 將所有的 HTTP 請求重定向到 HTTPS:

>>> r = requests.get('http://github.com')>>> r.url 'https://github.com/'>>> r.status_code 200>>> r.history [<Response [301]>]

如果你使用的是GET、OPTIONS、POST、PUT、PATCH 或者 DELETE,那么你可以通過?allow_redirects?參數禁用重定向處理:

>>> r = requests.get('http://github.com', allow_redirects=False) >>> r.status_code 301 >>> r.history []

如果你使用了 HEAD,你也可以啟用重定向:

>>> r = requests.head('http://github.com', allow_redirects=True) >>> r.url 'https://github.com/' >>> r.history [<Response [301]>]

超時

你可以告訴 requests 在經過以?timeout?參數設定的秒數時間之后停止等待響應。基本上所有的生產代碼都應該使用這一參數。如果不使用,你的程序可能會永遠失去響應:

>>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last):File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

注意

timeout?僅對連接過程有效,與響應體的下載無關。?timeout?并不是整個下載響應的時間限制,而是如果服務器在?timeout?秒內沒有應答,將會引發一個異常(更精確地說,是在timeout?秒內沒有從基礎套接字上接收到任何字節的數據時)If no timeout is specified explicitly, requests do not time out.

錯誤與異常

遇到網絡問題(如:DNS 查詢失敗、拒絕連接等)時,Requests 會拋出一個?ConnectionError?異常。

如果 HTTP 請求返回了不成功的狀態碼,?Response.raise_for_status()?會拋出一個?HTTPError異常。

若請求超時,則拋出一個?Timeout?異常。

若請求超過了設定的最大重定向次數,則會拋出一個?TooManyRedirects?異常。

所有Requests顯式拋出的異常都繼承自?requests.exceptions.RequestException?。

轉載于:https://www.cnblogs.com/StaYWARM/p/7604286.html

總結

以上是生活随笔為你收集整理的requests基础3的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。