一、Requests庫的安裝
利用 pip 安裝,如果你安裝了pip包(一款Python包管理工具,不知道可以百度喲),或者集成環境,比如Python(x,y)
或者anaconda的話,就可以直接使用pip安裝Python的庫。
1
|
$ pip install requests |
安裝完成之后,下面來看一下基本的方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#get請求方法 >>> r = requests.get( 'https://api.github.com/user' , auth = ( 'user' , 'pass' )) #打印get請求的狀態碼 >>> r.status_code 200 #查看請求的數據類型,可以看到是json格式,utf-8編碼 >>> r.headers[ 'content-type' ] 'application/json; charset=utf8' >>> r.encoding 'utf-8' #打印請求到的內容 >>> r.text u '{"type":"User"...' #輸出json格式數據 >>> r.json() {u 'private_gists' : 419 , u 'total_private_repos' : 77 , ...} |
下面看一個小栗子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
#小例子 import requests r = requests.get( 'http://www.baidu.com' ) print type (r) print r.status_code print r.encoding print r.text print r.cookies '''請求了百度的網址,然后打印出了返回結果的類型,狀態碼,編碼方式,Cookies等內容 輸出:''' < class 'requests.models.Response' > 200 UTF - 8 <RequestsCookieJar[]> |
二、http基本請求
requests庫提供了http所有的基本請求方式。例如:
1
2
3
4
5
|
r = requests.post( "http://httpbin.org/post" ) r = requests.put( "http://httpbin.org/put" ) r = requests.delete( "http://httpbin.org/delete" ) r = requests.head( "http://httpbin.org/get" ) r = requests.options(<a rel = "external nofollow" href = "http://httpbin.org/get" >http: / / httpbin.org / get< / a>) |
基本GET請求
1
2
3
4
5
6
7
8
|
r = requests.get( "http://httpbin.org/get" ) #如果想要加參數,可以利用 params 參數: import requests payload = { 'key1' : 'value1' , 'key2' : 'value2' } r = requests.get( "http://httpbin.org/get" , params = payload) print r.url #輸出:http://httpbin.org/get?key2=value2&key1=value1 |
如果想請求JSON文件,可以利用 json()
方法解析,例如自己寫一個JSON文件命名為a.json,內容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[ "foo" , "bar" , { "foo" : "bar" }] #利用如下程序請求并解析: import requests r = requests.get( "a.json" ) print r.text print r.json() '''運行結果如下,其中一個是直接輸出內容,另外一個方法是利用 json() 方法 解析,感受下它們的不同:''' [ "foo" , "bar" , { "foo" : "bar" }] [u 'foo' , u 'bar' , {u 'foo' : u 'bar' }] |
如果想獲取來自服務器的原始套接字響應,可以取得 r.raw
。 不過需要在初始請求中設置 stream=True
。
1
2
3
4
5
6
|
r = requests.get( 'https://github.com/timeline.json' , stream = True ) r.raw #輸出 <requests.packages.urllib3.response.HTTPResponse object at 0x101194810 > r.raw.read( 10 ) '\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03' |
這樣就獲取了網頁原始套接字內容。
如果想添加 headers,可以傳 headers 參數:
1
2
3
4
5
6
7
|
import requests payload = { 'key1' : 'value1' , 'key2' : 'value2' } headers = { 'content-type' : 'application/json' } r = requests.get( "http://httpbin.org/get" , params = payload, headers = headers) print r.url #通過headers參數可以增加請求頭中的headers信息 |
三、基本POST請求
對于 POST 請求來說,我們一般需要為它增加一些參數。那么最基本的傳參方法可以利用 data 這個參數。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import requests payload = { 'key1' : 'value1' , 'key2' : 'value2' } r = requests.post( "http://httpbin.org/post" , data = payload) print r.text #運行結果如下: { "args" : {}, "data" : "", "files" : {}, "form" : { "key1" : "value1" , "key2" : "value2" }, "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Content-Length" : "23" , "Content-Type" : "application/x-www-form-urlencoded" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" }, "json" : null, "url" : "http://httpbin.org/post" } |
可以看到參數傳成功了,然后服務器返回了我們傳的數據。
有時候我們需要傳送的信息不是表單形式的,需要我們傳JSON格式的數據過去,所以我們可以用 json.dumps()
方法把表單數據序列化。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import json import requests url = 'http://httpbin.org/post' payload = { 'some' : 'data' } r = requests.post(url, data = json.dumps(payload)) print r.text #運行結果: { "args" : {}, "data" : "{\"some\": \"data\"}" , "files" : {}, "form" : {}, "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Content-Length" : "16" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" }, "json" : { "some" : "data" }, "url" : "http://httpbin.org/post" } |
通過上述方法,我們可以POST JSON格式的數據
如果想要上傳文件,那么直接用 file 參數即可:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#新建一個 test.txt 的文件,內容寫上 Hello World! import requests url = 'http://httpbin.org/post' files = { 'file' : open ( 'test.txt' , 'rb' )} r = requests.post(url, files = files) print r.text { "args" : {}, "data" : "", "files" : { "file" : "Hello World!" }, "form" : {}, "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Content-Length" : "156" , "Content-Type" : "multipart/form-data; boundary=7d8eb5ff99a04c11bb3e862ce78d7000" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" }, "json" : null, "url" : "http://httpbin.org/post" } |
這樣我們便成功完成了一個文件的上傳。
requests 是支持流式上傳的,這允許你發送大的數據流或文件而無需先把它們讀入內存。要使用流式上傳,僅需為你的請求體提供一個類文件對象即可,非常方便:
1
2
|
with open ( 'massive-body' ) as f: requests.post( 'http://some.url/streamed' , data = f) |
四、Cookies
如果一個響應中包含了cookie,那么我們可以利用 cookies 變量來拿到:
1
2
3
4
5
6
|
import requests url = 'Example Domain' r = requests.get(url) print r.cookies print r.cookies[ 'example_cookie_name' ] |
以上程序僅是樣例,可以用 cookies 變量來得到站點的 cookies
另外可以利用 cookies 變量來向服務器發送 cookies 信息:
1
2
3
4
5
6
7
8
|
import requests url = 'http://httpbin.org/cookies' cookies = dict (cookies_are = 'working' ) r = requests.get(url, cookies = cookies) print r.text #輸出: '{"cookies": {"cookies_are": "working"}}' |
五、超時配置
可以利用 timeout 變量來配置最大請求時間
1
|
requests.get(‘Build software better, together', timeout = 0.001 ) |
注:timeout 僅對連接過程有效,與響應體的下載無關。
也就是說,這個時間只限制請求的時間。即使返回的 response 包含很大內容,下載需要一定時間。
六、會話對象
在以上的請求中,每次請求其實都相當于發起了一個新的請求。也就是相當于我們每個請求都用了不同的瀏覽器單獨打開的效果。也就是它并不是指的一個會話,即使請求的是同一個網址。比如:
1
2
3
4
5
6
7
8
9
|
import requests requests.get( 'http://httpbin.org/cookies/set/sessioncookie/123456789' ) r = requests.get( "http://httpbin.org/cookies" ) print (r.text) #結果是: { "cookies" : {} } |
很明顯,這不在一個會話中,無法獲取 cookies,那么在一些站點中,我們需要保持一個持久的會話怎么辦呢?就像用一個瀏覽器逛淘寶一樣,在不同的選項卡之間跳轉,這樣其實就是建立了一個長久會話。
解決方案如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
import requests s = requests.Session() s.get( 'http://httpbin.org/cookies/set/sessioncookie/123456789' ) r = s.get( "http://httpbin.org/cookies" ) print (r.text) #在這里我們請求了兩次,一次是設置 cookies,一次是獲得 cookies { "cookies" : { "sessioncookie" : "123456789" } } |
發現可以成功獲取到 cookies 了,這就是建立一個會話到作用。
那么既然會話是一個全局的變量,那么我們肯定可以用來全局的配置了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import requests s = requests.Session() s.headers.update({ 'x-test' : 'true' }) r = s.get( 'http://httpbin.org/headers' , headers = { 'x-test2' : 'true' }) print r.text '''通過 s.headers.update 方法設置了 headers 的變量。然后我們又在請求中 設置了一個 headers,那么會出現什么結果?很簡單,兩個變量都傳送過去了。 運行結果:''' { "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" , "X-Test" : "true" , "X-Test2" : "true" } } |
如果get方法傳的headers 同樣也是 x-test 呢?
1
2
3
4
5
6
7
8
9
10
11
12
|
r = s.get( 'http://httpbin.org/headers' , headers = { 'x-test' : 'true' }) #它會覆蓋掉全局的配置: { "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" , "X-Test" : "true" } } |
如果不想要全局配置中的一個變量了呢?很簡單,設置為 None 即可。
1
2
3
4
5
6
7
8
9
|
r = s.get( 'http://httpbin.org/headers' , headers = { 'x-test' : None }) { "headers" : { "Accept" : "*/*" , "Accept-Encoding" : "gzip, deflate" , "Host" : "http://httpbin.org" , "User-Agent" : "python-requests/2.9.1" } } |
以上就是 session 會話的基本用法。
七、SSL證書驗證
現在隨處可見 https 開頭的網站,Requests可以為HTTPS請求驗證SSL證書,就像web瀏覽器一樣。要想檢查某個主機的SSL證書,你可以使用 verify 參數,因為前段時間12306 證書不是無效的嘛,來測試一下:
1
2
3
4
5
6
|
import requests r = requests.get( 'https://kyfw.12306.cn/otn/' , verify = True ) print r.text #結果: requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c: 590 ) |
來試下 github 的:
1
2
3
4
|
import requests r = requests.get( 'Build software better, together' , verify = True ) print r.text |
嗯,正常請求,由于內容太多,我就不粘貼輸出了。
如果我們想跳過剛才 12306 的證書驗證,把 verify 設置為 False 即可:
1
2
3
4
|
import requests r = requests.get( 'https://kyfw.12306.cn/otn/' , verify = False ) print r.text |
發現就可以正常請求了。在默認情況下 verify 是 True,所以如果需要的話,需要手動設置下這個變量。
八、代理
如果需要使用代理,你可以通過為任意請求方法提供 proxies 參數來配置單個請求。
1
2
3
4
5
6
7
8
9
10
|
import requests proxies = { "https" : "http://41.118.132.69:4433" } r = requests.post( "http://httpbin.org/post" , proxies = proxies) print r.text #也可以通過環境變量 HTTP_PROXY 和 HTTPS_PROXY 來配置代理 export HTTP_PROXY = "http://10.10.1.10:3128" export HTTPS_PROXY = <a href = "http://10.10.1.10:1080" >http: / / 10.10 . 1.10 : 1080 < / a> |
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。