前言
之前我們用了 urllib 庫,這個作為入門的工具還是不錯的,對了解一些爬蟲的基本理念,掌握爬蟲爬取的流程有所幫助。入門之后,我們就需要學習一些更加高級的內容和工具來方便我們的爬取。那么這一節來簡單介紹一下 requests 庫的基本用法。
注:Python 版本依然基於 2.7
官方文檔
以下內容大多來自於官方文檔,本文進行了一些修改和總結。要了解更多可以參考
安裝
利用 pip 安裝
1
|
$ pip install requests
|
或者利用 easy_install
1
|
$ easy_install requests
|
通過以上兩種方法均可以完成安裝。
引入
首先我們引入一個小例子來感受一下
1
2
3
4
5
6
7
8
|
import requests
r = requests.get('http://cuiqingcai.com')
print type(r)
print r.status_code
print r.encoding
#print r.text
print r.cookies
|
以上代碼我們請求了本站點的網址,然后打印出了返回結果的類型,狀態碼,編碼方式,Cookies等內容。
運行結果如下
1
2
3
4
|
<class 'requests.models.Response'>
200
UTF-8
<RequestsCookieJar[]>
|
怎樣,是不是很方便。別急,更方便的在后面呢。
基本請求
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("http://httpbin.org/get")
|
嗯,一句話搞定。
基本GET請求
最基本的GET請求可以直接用get方法
1
|
r = requests.get("http://httpbin.org/get")
|
如果想要加參數,可以利用 params 參數
1
2
3
4
5
|
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print r.url
|
運行結果
1
|
http://httpbin.org/get?key2=value2&key1=value1
|
如果想請求JSON文件,可以利用 json() 方法解析
例如自己寫一個JSON文件命名為a.json,內容如下
1
2
3
|
["foo", "bar", {
"foo": "bar"
}]
|
利用如下程序請求並解析
1
2
3
4
5
|
import requests
r = requests.get("a.json")
print r.text
print r.json()
|
運行結果如下,其中一個是直接輸出內容,另外一個方法是利用 json() 方法解析,感受下它們的不同
1
2
3
4
|
["foo", "bar", {
"foo": "bar"
}]
[u'foo', u'bar', {u'foo': u'bar'}]
|
如果想獲取來自服務器的原始套接字響應,可以取得 r.raw 。 不過需要在初始請求中設置 stream=True 。
1
2
3
4
5
|
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
|
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
|
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text
|
運行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
{
"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": "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
|
import json
import requests
url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
print r.text
|
運行結果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
{
"args": {},
"data": "{\"some\": \"data\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "16",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
},
"json": {
"some": "data"
},
"url": "http://httpbin.org/post"
}
|
通過上述方法,我們可以POST JSON格式的數據
如果想要上傳文件,那么直接用 file 參數即可
新建一個 a.txt 的文件,內容寫上 Hello World!
1
2
3
4
5
6
|
import requests
url = 'http://httpbin.org/post'
files = {'file': open('test.txt', 'rb')}
r = requests.post(url, files=files)
print r.text
|
可以看到運行結果如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
{
"args": {},
"data": "",
"files": {
"file": "Hello World!"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "156",
"Content-Type": "multipart/form-data; boundary=7d8eb5ff99a04c11bb3e862ce78d7000",
"Host": "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 = 'http://example.com'
r = requests.get(url)
print r.cookies
print r.cookies['example_cookie_name']
|
以上程序僅是樣例,可以用 cookies 變量來得到站點的 cookies
另外可以利用 cookies 變量來向服務器發送 cookies 信息
1
2
3
4
5
6
|
import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print r.text
|
運行結果
1
|
'{"cookies": {"cookies_are": "working"}}'
|
可以已經成功向服務器發送了 cookies
超時配置
可以利用 timeout 變量來配置最大請求時間
1
|
requests.get('http://github.com', timeout=0.001)
|
注:timeout 僅對連接過程有效,與響應體的下載無關。
也就是說,這個時間只限制請求的時間。即使返回的 response 包含很大內容,下載需要一定時間,然而這並沒有什么卵用。
會話對象
在以上的請求中,每次請求其實都相當於發起了一個新的請求。也就是相當於我們每個請求都用了不同的瀏覽器單獨打開的效果。也就是它並不是指的一個會話,即使請求的是同一個網址。比如
1
2
3
4
5
|
import requests
requests.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = requests.get("http://httpbin.org/cookies")
print(r.text)
|
結果是
1
2
3
|
{
"cookies": {}
}
|
很明顯,這不在一個會話中,無法獲取 cookies,那么在一些站點中,我們需要保持一個持久的會話怎么辦呢?就像用一個瀏覽器逛淘寶一樣,在不同的選項卡之間跳轉,這樣其實就是建立了一個長久會話。
解決方案如下
1
2
3
4
5
6
|
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
運行結果
1
2
3
4
5
|
{
"cookies": {
"sessioncookie": "123456789"
}
}
|
發現可以成功獲取到 cookies 了,這就是建立一個會話到作用。體會一下。
那么既然會話是一個全局的變量,那么我們肯定可以用來全局的配置了。
1
2
3
4
5
6
|
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,那么會出現什么結果?
很簡單,兩個變量都傳送過去了。
運行結果
1
2
3
4
5
6
7
8
9
10
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1",
"X-Test": "true",
"X-Test2": "true"
}
}
|
如果get方法傳的headers 同樣也是 x-test 呢?
1
|
r = s.get('http://httpbin.org/headers', headers={'x-test': 'true'})
|
嗯,它會覆蓋掉全局的配置
1
2
3
4
5
6
7
8
9
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1",
"X-Test": "true"
}
}
|
那如果不想要全局配置中的一個變量了呢?很簡單,設置為 None 即可
1
|
r = s.get('http://httpbin.org/headers', headers={'x-test': None})
|
運行結果
1
2
3
4
5
6
7
8
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
}
}
|
嗯,以上就是 session 會話的基本用法
SSL證書驗證
現在隨處可見 https 開頭的網站,Requests可以為HTTPS請求驗證SSL證書,就像web瀏覽器一樣。要想檢查某個主機的SSL證書,你可以使用 verify 參數
現在 12306 證書不是無效的嘛,來測試一下
1
2
3
4
|
import requests
r = requests.get('https://kyfw.12306.cn/otn/', verify=True)
print r.text
|
結果
1
|
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
|
果真如此
來試下 github 的
1
2
3
4
|
import requests
r = requests.get('https://github.com', 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
|
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 來配置代理
1
2
|
export HTTP_PROXY="http://10.10.1.10:3128"
export HTTPS_PROXY="http://10.10.1.10:1080"
|
通過以上方式,可以方便地設置代理。
API
以上講解了 requests 中最常用的參數,如果需要用到更多,請參考官方文檔 API
結語
以上總結了一下 requests 的基本用法,如果你對爬蟲有了一定的基礎,那么肯定可以很快上手,在此就不多贅述了。
練習才是王道,大家盡快投注於實踐中吧。