爬蟲入門(二):Requests 庫用法大全

學習之前

在瞭解完爬蟲相關的基礎知識以後,我們就可以嘗試去開發自己的爬蟲程序了。我們使用的是 Python 語言來開發爬蟲,其中不得不學習的就是關於 requests 庫的使用了,下面就從 Python 的 requests 庫開始我們的爬蟲學習之路。
在這裏插入圖片描述

安裝 requests 庫

因爲學習過程使用的是 Python 語言,需要提前安裝 Python ,我安裝的是 Python 3.8 ,可以通過命令 python -V 查看自己安裝的 Python 版本,建議安裝 Python 3.X 以上的版本。
在這裏插入圖片描述安裝好 Python 以後可以 直接通過以下命令安裝 requests 庫。

pip3 install requests

安裝過程可能會因爲版本問題出現安裝失敗的情況,自行百度報錯內容就好了,基本都能五分鐘搞定。
爲了演示功能,我這裏使用 nginx 模擬了一個簡單網站。
下載好了以後,直接運行根目錄下的 nginx.exe 程序就可以了(備註:win環境下)。
這時本機訪問 :http://127.0.0.1 ,會進入 nginx 的一個默認頁面。
在這裏插入圖片描述

獲取網頁

下面我們開始用 requests 模擬一個請求,獲取頁面源代碼。

import requests  

r = requests.get('http://127.0.0.1')  
print(r.text)

執行以後得到的結果如下:

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

關於請求

常見的請求有很多種,比如上面的示例使用的就是 GET 請求,這裏詳細介紹一下這些常見的請求方法。
關於請求的測試,這裏介紹一個網站 :http://httpbin.org/ ,這個網站能測試 HTTP 請求和響應的各種信息,比如 cookie、ip、headers 和登錄驗證等,且支持 GET、POST 等多種方法,對 web 開發和測試很有幫助。
它用 Python + Flask 編寫,是一個開源項目。

GET 請求

發起請求

我們使用相同的方法,發起一個 GET 請求:

import requests  

r = requests.get('http://httpbin.org/get')  
print(r.text)

返回結果如下:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.23.0", 
    "X-Amzn-Trace-Id": "Root=1-5ec8c17c-4918b13bbf9452a586e40b01"
  }, 
  "origin": "223.88.74.214", 
  "url": "http://httpbin.org/get"
}

通過返回結果,我們可以看到返回結果所包括的信息有:Headers、URL、IP等。

添加參數

平時我們訪問的 URL 會包含一些參數,比如:id是100,name是YOOAO。正常的訪問,我們會編寫如下 URL 進行訪問:

http://httpbin.org/get?id=100&name=YOOAO

如果按照這樣的方式,我們的請求代碼就會變成:

r = requests.get('http://httpbin.org/get?id=100&name=YOOAO')  

顯然很不方便,而且參數多的情況下會容易出錯,這時我們可以通過 params 參數優化輸入內容。

import requests  

data = {  
    'id': '100',  
    'name': 'YOOAO'
}  

r = requests.get('http://httpbin.org/get', params=data)  
print(r.text)

這是執行代碼返回的結果如下:

{
  "args": {
    "id": "100", 
    "name": "YOOAO"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.23.0", 
    "X-Amzn-Trace-Id": "Root=1-5ec8c656-e2d19f88cfa93600372917b8"
  }, 
  "origin": "223.88.74.214", 
  "url": "http://httpbin.org/get?id=100&name=YOOAO"
}

通過返回結果,我們可以看到,通過字典方式傳輸的參數被自動構造成了完整的 URL ,不需要我們自己手動完成構造。

返回結果處理

返回結果是 JSON 格式,因此我們可以使用調用 json 的方法來解析。如果返回內容不是 JSON 格式,這種調用會報錯。

import requests  

r = requests.get('http://httpbin.org/get')  
print(type(r.text))   
print(type(r.json()))

返回結果:

<class 'str'>
<class 'dict'>

內容抓取

這裏我們使用簡單的正則表達式,來抓取 nginx 示例頁面種所有 < a > 標籤的內容,代碼如下:

import requests  
import re

r = requests.get('http://127.0.0.1')  
pattern = re.compile('<a.*?>(.*?)</a>', re.S)
a_content = re.findall(pattern, r.text)
print(a_content)

抓取結果:

['nginx.org', 'nginx.com']

這裏一次簡單的頁面獲取和內容抓取就完成了,其中關於正則表達的使用是爬蟲的基礎知識,十分重要,下一篇文章將詳細介紹正則表達式的是如何使用。

數據文件下載

上面的示例,返回的都是頁面信息,如果我們想獲取網頁上的圖片、音頻和視頻文件,我們就需要學會抓取頁面的二進制數據。比如我上一篇博文封面的小姐姐很好看,我們就用爬蟲來抓取這張圖片。
首先我們通過查看源代碼,獲取到了這個圖片的鏈接:

https://img-blog.csdnimg.cn/20200512221903237.jpg

我們可以使用 open 方法來完成圖片等二進制文件的下載,示例代碼:

import requests

r = requests.get('https://img-blog.csdnimg.cn/20200512221903237.jpg')
with open('image.jpg', 'wb') as f:
    f.write(r.content)
print('下載完成。')

open 方法種,它的第一個參數是文件名稱,第二個參數代表以二進制的形式打開,可以向文件裏寫入二進制數據。
運行結束以後,會在運行文件的同級文件夾下保存下載下來的圖片。運用同樣原理,我們可以處理視頻和音頻文件。

添加headers

在上面的示例中,我們直接發起的請求,沒有添加 headers ,某些網站爲因爲請求不攜帶請求頭而造成訪問異常,這裏我們可以手動添加 headers 內容,模擬添加 headers 中的 Uer-Agent 內容代碼:

import requests

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36'}
r = requests.get('http://httpbin.org/get', headers=headers)
print(r.text)

執行結果:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36", 
    "X-Amzn-Trace-Id": "Root=1-5ec8f342-8a9f986011eac8f07be8b450"
  }, 
  "origin": "223.88.74.214", 
  "url": "http://httpbin.org/get"
}

結果可見,User-Agent 的值變了。不是之前的:python-requests/2.23.0。

POST 請求

GET請求相關的知識都講完了,下面講講另一個常見的請求方式:POST 請求。
使用 requests 實現 POST 請求的代碼如下:

import requests

data = {  
    'id': '100',  
    'name': 'YOOAO'
}  

r = requests.post("http://httpbin.org/post", data=data)
print(r.text)

執行結果:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "id": "100", 
    "name": "YOOAO"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "17", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.23.0", 
    "X-Amzn-Trace-Id": "Root=1-5ec8f4a0-affca27a05e320a84ca6535a"
  }, 
  "json": null, 
  "origin": "223.88.74.214", 
  "url": "http://httpbin.org/post"
}

從 form 中我們看到了自己提交的數據,可見我們的 POST 請求訪問成功。

響應

訪問URL時,有請求就會有響應,上面的示例使用 text 和 content 獲取了響應的內容。
除此以外,還有很多屬性和方法可以用來獲取其他信息,比如狀態碼、響應頭、Cookies 等。

import requests

r = requests.get('http://127.0.0.1/')
print(type(r.status_code), r.status_code)
print(type(r.headers), r.headers)
print(type(r.cookies), r.cookies)
print(type(r.url), r.url)
print(type(r.history), r.history)

相應結果:

<class 'int'> 200
<class 'requests.structures.CaseInsensitiveDict'> {'Server': 'nginx/1.17.10', 'Date': 'Sat, 23 May 2020 10:08:09 GMT', 'Content-Type': 'text/html', 'Content-Length': '612', 'Last-Modified': 'Tue, 14 Apr 2020 14:19:26 GMT', 'Connection': 'keep-alive', 'ETag': '"5e95c66e-264"', 'Accept-Ranges': 'bytes'}
<class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
<class 'str'> http://127.0.0.1/
<class 'list'> []

關於狀態碼,requests 還提供了一個內置的狀態碼查詢對象 requests.codes,用法示例如下:

import requests

r = requests.get('http://127.0.0.1/')
exit() if not r.status_code == requests.codes.ok else print('Request Successfully')


==========執行結果==========
Request Successfully

這裏通過比較返回碼和內置的成功的返回碼,來保證請求得到了正常響應,輸出成功請求的消息,否則程序終止。
這裏我們用 requests.codes.ok 得到的是成功的狀態碼 200。
這樣的話,我們就不用再在程序裏面寫狀態碼對應的數字了,用字符串表示狀態碼會顯得更加直觀。
下面是響應碼和查詢條件對照信息:

# 信息性狀態碼  
100: ('continue',),  
101: ('switching_protocols',),  
102: ('processing',),  
103: ('checkpoint',),  
122: ('uri_too_long', 'request_uri_too_long'),  

# 成功狀態碼  
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),  
201: ('created',),  
202: ('accepted',),  
203: ('non_authoritative_info', 'non_authoritative_information'),  
204: ('no_content',),  
205: ('reset_content', 'reset'),  
206: ('partial_content', 'partial'),  
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),  
208: ('already_reported',),  
226: ('im_used',),  

# 重定向狀態碼  
300: ('multiple_choices',),  
301: ('moved_permanently', 'moved', '\\o-'),  
302: ('found',),  
303: ('see_other', 'other'),  
304: ('not_modified',),  
305: ('use_proxy',),  
306: ('switch_proxy',),  
307: ('temporary_redirect', 'temporary_moved', 'temporary'),  
308: ('permanent_redirect',  
      'resume_incomplete', 'resume',), # These 2 to be removed in 3.0  

# 客戶端錯誤狀態碼  
400: ('bad_request', 'bad'),  
401: ('unauthorized',),  
402: ('payment_required', 'payment'),  
403: ('forbidden',),  
404: ('not_found', '-o-'),  
405: ('method_not_allowed', 'not_allowed'),  
406: ('not_acceptable',),  
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),  
408: ('request_timeout', 'timeout'),  
409: ('conflict',),  
410: ('gone',),  
411: ('length_required',),  
412: ('precondition_failed', 'precondition'),  
413: ('request_entity_too_large',),  
414: ('request_uri_too_large',),  
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),  
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),  
417: ('expectation_failed',),  
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),  
421: ('misdirected_request',),  
422: ('unprocessable_entity', 'unprocessable'),  
423: ('locked',),  
424: ('failed_dependency', 'dependency'),  
425: ('unordered_collection', 'unordered'),  
426: ('upgrade_required', 'upgrade'),  
428: ('precondition_required', 'precondition'),  
429: ('too_many_requests', 'too_many'),  
431: ('header_fields_too_large', 'fields_too_large'),  
444: ('no_response', 'none'),  
449: ('retry_with', 'retry'),  
450: ('blocked_by_windows_parental_controls', 'parental_controls'),  
451: ('unavailable_for_legal_reasons', 'legal_reasons'),  
499: ('client_closed_request',),  

# 服務端錯誤狀態碼  
500: ('internal_server_error', 'server_error', '/o\\', '✗'),  
501: ('not_implemented',),  
502: ('bad_gateway',),  
503: ('service_unavailable', 'unavailable'),  
504: ('gateway_timeout',),  
505: ('http_version_not_supported', 'http_version'),  
506: ('variant_also_negotiates',),  
507: ('insufficient_storage',),  
509: ('bandwidth_limit_exceeded', 'bandwidth'),  
510: ('not_extended',),  
511: ('network_authentication_required', 'network_auth', 'network_authentication')

requests 用法進階

文件上傳

之前已經模擬了傳遞參數,同樣的方法可以測試上傳文件,我本以上傳本地的圖片爲例,代碼如下:

在這裏插入代碼片

運行結果:

{
  "args": {}, 
  "data": "", 
  "files": {
    "file": "data:application/octet-stream;base64,/9j/4AAQSkZJRgABAQAAAQABAAD....(省略具體內容)/NfOamniFcAqbjkRuJxEyZlmbVsOb0nI6qd1PiDJ6jjsTm+8aZplcl7aLVZadRCrsbXG6E8u8TULUEIegVF5Qj1gXvA//9k="
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "4816", 
    "Content-Type": "multipart/form-data; boundary=fe6d94bb76a53d2af0d0539ad823c330", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.23.0", 
    "X-Amzn-Trace-Id": "Root=1-5ec91c97-c609fababa034b385bdfeaf0"
  }, 
  "json": null, 
  "origin": "223.88.74.214", 
  "url": "http://httpbin.org/post"
}

從返回結果可以看出,有一個 files 字段來存儲文件信息。

Cookies

前面一節的學習,我們瞭解到 Cookies 的重要性,使用 requests 來獲取和設置 Cookies 同樣十分簡單。
Cookies 的獲取示例代碼:

import requests

r = requests.get('http://www.baidu.com')
print(r.cookies)
for key, value in r.cookies.items():
    print(key + '=' + value)

執行結果:

<RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]>
BDORZ=27315

有些網站需要登陸以後才能訪問,這時候我們可以直接使用 Cookies 來維持登錄狀態。
打開我的 CSDN 賬戶,下面是登錄以後的 Cookies 信息,可以明顯看到我的賬戶信息。
在這裏插入圖片描述以百度首頁爲例,在沒有設置 Cookies 的情況下直接訪問,返回結果如下圖:
在這裏插入圖片描述在添加請求頭信息後返回結果如下圖,明顯可以看到我的用戶名信息:
在這裏插入圖片描述示例代碼:

import requests

cookies = 'COOKIE_SESSION=............H_PS_PSSID=1447_31670_21083'
jar = requests.cookies.RequestsCookieJar()
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36'
}
for cookie in cookies.split(';'):
    key, value = cookie.split('=', 1)
    jar.set(key, value)
r = requests.get('https://www.baidu.com/?tn=78040160_14_pg&ch=16', cookies=jar, headers=headers)

print(r.cookies)
for key, value in r.cookies.items():
	print(key + '=' + value)
print('====頁面內容===')
print(r.text)

Session 維持

當我們用 get 和 post 方法去模擬頁面請求時,相對於每個請求都是通過不同的瀏覽器去訪問的,沒有辦法做到 Session 的維持,我們雖然可以通過設置 Cookies 的方式來解決,但是太麻煩了,這裏我們介紹一個簡單的實現方法。

還是需要使用 http://httpbin.org 這個網站,我們不做任何操作,直接請求兩次:

import requests
#訪問一個鏈接,並在cookies 中設置一個值
requests.get('http://httpbin.org/cookies/set/id/10086')
#再次訪問這個鏈接
r = requests.get('http://httpbin.org/cookies')
print(r.text)

======執行結果=======
{
  "cookies": {}
}

這裏我們創建一個 Session 對象以後再試一下,可以看到成功獲取到了設置的值:

import requests

s = requests.Session()
s.get('http://httpbin.org/cookies/set/id/10086')
r = s.get('http://httpbin.org/cookies')
print(r.text)


======執行結果=======
{
  "cookies": {
    "id": "10086"
  }
}

SSL 證書驗證

現在很多網站都會驗證證書,我們可以設置參數來忽略證書的驗證。

import requests

response = requests.get('https://XXXXXXXX', verify=False)
print(response.status_code)

或者制定本地證書作爲客戶端證書:

import requests

response = requests.get('https://xxxxxx', cert=('/path/server.crt', '/path/server.key'))
print(response.status_code)

注意:本地私有證書的 key 必須是解密狀態,加密狀態的 key 是不支持的。

設置超時

很多時候我們需要設置超時時間來控制訪問的效率,遇到訪問慢的鏈接直接跳過。
示例代碼:

import requests
# 設置超時時間爲 10 秒
r = requests.get('https://httpbin.org/get', timeout=10)
print(r.status_code)

將連接時間和讀取時間分開計算:

r = requests.get('https://httpbin.org/get', timeout=(3, 10))

不添加參數,默認不設置超時時間,等同於:

r = requests.get('https://httpbin.org/get', timeout=None)

身份認證

遇到一些網站需要輸入用戶名和密碼,我們可以通過 auth 參數進行設置。

import requests  
from requests.auth import HTTPBasicAuth  
# 用戶名爲 admin ,密碼爲 admin 
r = requests.get('https://xxxxxx/', auth=HTTPBasicAuth('admin', 'admin'))  
print(r.status_code)

簡化寫法:

import requests

r = requests.get('https://xxxxxx', auth=('admin', 'admin'))
print(r.status_code)

設置代理

如果頻繁的訪問某個網站時,後期會被一些反爬程序識別,要求輸入驗證信息,或者其他信息,甚至IP被封無法再次訪問,這時候,我們可以通過設置代理來避免這樣的問題。

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

若你的代理需要使用HTTP Basic Auth,可以使用 http://user:password@host/ 語法:

proxies = {
    "http": "http://user:[email protected]:3128/",
}

要爲某個特定的連接方式或者主機設置代理,使用 scheme://hostname 作爲 key, 它會針對指定的主機和連接方式進行匹配。

proxies = {'http://10.20.1.128': 'http://10.10.1.10:5323'}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章