python3—requests講解

requests庫是一個常用的用於http請求的模塊,它使用python語言編寫,可以方便的對網頁進行爬取,是學習python爬蟲的較好的http請求模塊。

1、requests模塊的安裝

WIN+R——cmd——pip install requests即可。

如果遇到read timeout(訪問超時)的問題,可參考鏈接文章: 中you-get工具借用豆瓣代理的下載安裝方式。

2、requests模塊的使用方法

2.1 requests庫的幾個主要方法:

python3—requests講解

(1)requests.get()

這個方法是我們平時最常用的方法之一,通過這個方法我們可以瞭解到其他的方法,所以我們詳細介紹這個方法。 具體參數是:

<code>r=requests.get(url,params,**kwargs)/<code>
  • url: 需要爬取的網站地址。
  • params: 翻譯過來就是參數, url中的額外參數,字典或者字節流格式,可選。
  • **kwargs : 12個控制訪問的參數

params:字典或字節序列, 作為參數增加到url中,使用這個參數可以把一些鍵值對以?key1=value1&key2=value2的模式增加到url中 例如:kw= {'key1':' values', 'key2': 'values'} r = requests.get('http:www.python123.io/ws', params=kw)

a.發送無參數的get請求:


python3—requests講解

b.發送帶參數的get請求:


python3—requests講解

<strong>以上得知,我們的get參數是以params關鍵字參數傳遞的。

<strong>此外,還可以傳遞一個list給一個請求參數:


python3—requests講解

以上就是get請求的基本形式。

**kwargs有以下的參數:

  • data:字典,字節序或文件對象,重點作為向服務器提供或提交資源是提交,,作為requests的內容,與params不同的是,data提交的數據並不放在url鏈接裡, 而是放在url鏈接對應位置的地方作為數據來存儲。它也可以接受一個字符串對象。
  • json:json格式的數據, json合適在相關的html,http相關的web開發中非常常見, 也是http最經常使用的數據格式, 他是作為內容部分可以向服務器提交。 例如:kv = {'key1': 'value1'} r = requests.post('http://python123.io/ws', json=kv)
  • headers:字典是http的相關語,對應了向某個url訪問時所發起的http的頭i字段, 可以用這個字段來定義http的訪問的http頭,可以用來模擬任何我們想模擬的瀏覽器來對url發起訪問。 例子: hd = {'user-agent': 'Chrome/10'} r = requests.post('http://python123.io/ws', headers=hd)
  • cookies:字典或CookieJar,指的是從http中解析cookie
  • auth:元組,用來支持http認證功能
  • files:字典, 是用來向服務器傳輸文件時使用的字段。 例子:fs = {'files': open('data.txt', 'rb')} r = requests.post('http://python123.io/ws', files=fs)
  • timeout: 用於設定超時時間, 單位為秒,當發起一個get請求時可以設置一個timeout時間, 如果在timeout時間內請求內容沒有返回, 將產生一個timeout的異常。
  • proxies:字典, 用來設置訪問代理服務器。
  • allow_redirects: 開關, 表示是否允許對url進行重定向, 默認為True。
  • stream: 開關, 指是否對獲取內容進行立即下載, 默認為True。
  • verify:開關, 用於認證SSL證書, 默認為True。
  • cert: 用於設置保存本地SSL證書路徑

其中response(即:r)對象有以下屬性:


python3—requests講解

我們可以單擊桌面左下角的WIN按鈕,找到python安裝包,打開IDLE來親自操作熟悉response的屬性。

python3—requests講解


python3—requests講解

requests庫的異常

注意requests庫有時會產生異常,比如網絡連接錯誤、http錯誤異常、重定向異常、請求url超時異常等等。所以我們需要判斷r.status_codes是否是200,在這裡我們怎麼樣去捕捉異常呢?

這裡我們可以利用r.raise_for_status() 語句去捕捉異常,該語句在方法內部判斷r.status_code是否等於200,如果不等於,則拋出異常。

於是在這裡我們有一個爬取網頁的通用代碼框架:

python3—requests講解

此處不能採用return來返回輸出,使用的話會報錯,因為:<strong>return只能用在自定義函數中。

(2) request.head()

看代碼:

python3—requests講解

(3)requests.post()

1、向url post一個字典:


python3—requests講解


2、向url post 一個字符串,自動編碼為data

<code>>>> import requests>>> r=requests.post("http://httpbin.org/post",data="hello python")>>> print(r.text){  "args": {},   "data": "hello python",   "files": {},   "form": {},   "headers": {    "Accept": "*/*",     "Accept-Encoding": "gzip, deflate",     "Content-Length": "12",     "Host": "httpbin.org",     "User-Agent": "python-requests/2.22.0",     "X-Amzn-Trace-Id": "Root=1-5e510c68-12ee4eec533847d89a06d184"  },   "json": null,   "origin": "36.47.128.206",   "url": "http://httpbin.org/post"}/<code>

3.向url post一個文件

<code>>>> import requests>>> files = {'files':open('C:\\\\Users\\\\Think\\\\Desktop\\\\test_requests\\\\test.txt','rb')}>>> r = requests.post('https://httpbin.org/post',files=files)>>> print(r.text){    "args":{     },    "data":"",    "files":{        "files":"hello worle!"    },    "form":{     },    "headers":{        "Accept":"*/*",        "Accept-Encoding":"gzip, deflate",        "Connection":"close",        "Content-Length":"158",        "Content-Type":"multipart/form-data; boundary=d2fb307f28aeb57b932d867f80f2f600",        "Host":"httpbin.org",        "User-Agent":"python-requests/2.19.1"    },    "json":null,    "origin":"113.65.2.187",    "url":"https://httpbin.org/post"/<code>

以上得知,post請求參數是以data關鍵字參數來傳遞的。

(5)requests.put()

看代碼:

<code>>>> payload={"key1":"value1","key2":"value2"}>>> r=requests.put("http://httpbin.org/put",data=payload)>>> print(r.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.18.4"  },   "json": null,   "origin": "218.197.153.150",   "url": "http://httpbin.org/put"/<code>

(6)requests.patch()

requests.patch和request.put類似。 兩者不同的是: 當我們用patch時僅需要提交需要修改的字段。 而用put時,必須將20個字段一起提交到url,未提交字段將會被刪除。 patch的好處是:節省網絡帶寬。

(7)requests.request()

requests.request()支持其他所有的方法。 requests.request(method,url,**kwargs)

  • method: “GET”、”HEAD”、”POST”、”PUT”、”PATCH”等等
  • url: 請求的網址
  • **kwargs: 控制訪問的參數


分享到:


相關文章: