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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python requests库的简单使用

發布時間:2025/3/20 python 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python requests库的简单使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似,但比urllib,urllib2更加使用簡單。

1. requests庫的安裝
在你的終端中運行pip安裝命令即可

pip install requests

  

使用源碼安裝

git clone git://github.com/kennethreitz/requests.git python setup.py install

  

2. requests發送請求
使用 Requests 發送網絡請求

import requestsreq0 = requests.get("https://www.baidu.com") print (req0)

  

# 發送一個 HTTP POST 請求

req1 = requests.post("https://http://httpbin.org/post")

  

# 發送PUT,DELETE,HEAD 以及 OPTIONS 請求

requests.put("http://http://httpbin.org/put") requests.delete("http://http://httpbin.org/delete") requests.head("http://http://httpbin.org/get") requests.options("http://http://httpbin.org/get")

  


3. 傳遞URL 參數
Requests 使用 params 關鍵字參數,以一個字典來提供這些參數

payload = {'key1': 'value1', 'key2': 'value2'} req2 = requests.get("https://httpbin.org/get",params=payload) print (req2.url) # https://httpbin.org/get?key2=value2&key1=value1

  

# 注:字典里值為 None 的鍵都不會被添加到 URL 的查詢字符串里

將一個列表作為值傳入

payload = {'key1': 'value1', 'key2': ['value2', 'value3']} req3 = requests.get('http://httpbin.org/get', params=payload) print (req3.url) # http://httpbin.org/get?key2=value2&key2=value3&key1=value1

  


4. 響應內容
requests 讀取服務器響應的內容

import requests req4 = requests.get("https://www.baidu.com") print (req4.text)

  

Requests 會自動解碼來自服務器的內容。大多數 unicode 字符集都能被無縫地解碼,使用req4.encoding 屬性可以查詢編碼格式和改變編碼類型

>>> req4.encoding 'ISO-8859-1' >>> req4.encoding = 'utf-8' >>> req4.encoding 'utf-8'

  

5. 二進制響應內容
Requests 會自動為你解碼 gzip 和 deflate 傳輸編碼的響應數據

print (req4.content)

  

6. JSON 響應內容
Requests 中也有一個內置的 JSON 解碼器,幫助處理 JSON 數據

import requests req6 = requests.get("https://github.com/timeline.json") print (req6.json)

  

# 如果 JSON 解碼失敗, r.json 就會拋出一個異常。例如,相應內容是 401 (Unauthorized),嘗試訪問 r.json 將會拋出 ValueError: No JSON object could be decoded 異常

7. 原始響應內容
想獲取來自服務器的原始套接字響應,可以訪問 r.raw. 不過先要確保在初始請求中設置了 stream=True

req7 = requsets.get('https://github.com/timeline.json',stream = True) print (req7.raw) print (req7.raw.read(10))

  

8. 定制請求頭
為請求添加 HTTP 頭部,只要簡單地傳遞一個 dict 給 headers 參數就可以了

url = 'https://api.github.com/some/endpoint' headers = {'user-agent': 'my-app/0.0.1'} req8 = requests.get(url, headers=headers)

  

注:注意: 所有的 header 值必須是 string、bytestring 或者 unicode

9. 更加復雜的 POST 請求
發送一些編碼為表單形式的數據——非常像一個 HTML 表單。要實現這個,只需簡單地傳遞一個字典給 data 參數。數據字典在發出請求時會自動編碼為表單形式

payload = {'key1':'value1','key2':'value2'} req9 = requests.post("http://httpbin.org/post", data=payload) print (req9.text) ''' { "args": {}, "data": "", "files": {}, "form": { "key1": "value1", "key2": "value2" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Connection": "close", "Content-Length": "23", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.6.0 CPython/2.7.5 Linux/3.10.0-327.36.1.el7.x86_64" }, "json": null, "origin": "112.35.10.78", "url": "http://httpbin.org/post" } '''

  

傳遞一個 string 而不是一個 dict,那么數據會被直接發布出去

import json url = 'https://api.github.com/some/endpoint' payload = {'some':'data'} req10 = requests.post(url,data=json.dumps(payload)) print (req10) # {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}

  

10. POST一個多部分編碼(Multipart-Encoded)的文件

Requests 使得上傳多部分編碼文件變得很簡單

url = 'http://httpbin.org/post' files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')} r = requests.post(url, files=files) r.text ''' { ... "files": { "file": "some,data,to,send\\nanother,row,to,send\\n" }, ... } '''

  

11. 響應狀態碼
檢測響應狀態碼

req11 = requests.get('http://httpbin.org/get') req11.status_code # 200

  

Requests還附帶了一個內置的狀態碼查詢對象

req11.status_code == requests.codes.ok # True

  

12. 響應頭
查看以一個 Python 字典形式展示的服務器響應頭

req11.headers ''' {'content-length': '311', 'via': '1.1 vegur', 'x-powered-by': 'Flask', 'server': 'meinheld/0.6.1', 'connection': 'keep-alive', 'x-processed-time': '0.000663995742798', 'access-control-allow-credentials': 'true', 'date': 'Fri, 19 May 2017 12:38:25 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json'} '''

  


注: 響應頭的字典比較特殊:它是僅為 HTTP 頭部而生的。HTTP 頭部是大小寫不敏感的

13. Cookie
如果響應中包含一些 cookie,你可以快速訪問它們

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

  

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

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

  

14. 重定向與請求歷史
使用響應對象的 history 方法來追蹤重定向
Response.history 是一個 Response 對象的列表,為了完成請求而創建了這些對象。這個對象列表按照從最老到最近的請求進行排序

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

  

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

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

  

使用了 HEAD,可以啟用重定向

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

  

15. 超時
requests 在經過以 timeout 參數設定的秒數時間之后停止等待響應
注:timeout 僅對連接過程有效,與響應體的下載無關。 timeout 并不是整個下載響應的時間限制,而是如果服務器在 timeout 秒內沒有應答,將會引發一個異常(更精確地說,是在 timeout 秒內沒有從基礎套接字上接收到任何字節的數據時)

16. 錯誤與異常
(1) 遇到網絡問題(如:DNS 查詢失敗、拒絕連接等)時,Requests 會拋出一個 ConnectionError 異常。
(2) 如果 HTTP 請求返回了不成功的狀態碼, Response.raise_for_status() 會拋出一個 HTTPError 異常。
(3) 若請求超時,則拋出一個 Timeout 異常。
(4) 若請求超過了設定的最大重定向次數,則會拋出一個 TooManyRedirects 異常。
(5) 所有Requests顯式拋出的異常都繼承自 requests.exceptions.RequestException 。

?

參考鏈接:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html

?

轉載于:https://www.cnblogs.com/xieshengsen/p/6886164.html

總結

以上是生活随笔為你收集整理的python requests库的简单使用的全部內容,希望文章能夠幫你解決所遇到的問題。

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