上一篇文章: Python3網絡爬蟲實戰---2三、使用Urllib:分析Robots協議
下一篇文章:
在前面一節咱們瞭解了 Urllib 的基本用法,可是其中確實有不方便的地方。好比處理網頁驗證、處理 Cookies 等等,須要寫 Opener、Handler 來進行處理。爲了更加方便地實現這些操做,在這裏就有了更爲強大的庫 Requests,有了它,Cookies、登陸驗證、代理設置等等的操做都不是事兒。html
那麼接下來就讓咱們來領略一下它的強大之處吧。python
本節咱們首先來了解下 Requests 庫的基本使用方法。git
在本節開始以前請確保已經正確安裝好了 Requests 庫,若是沒有安裝能夠參考第一章的安裝說明。github
在 Urllib 庫中有 urlopen() 的方法,實際上它是以 GET 方式請求了一個網頁。
那麼在 Requests 中,相應的方法就是 get() 方法,是否是感受表達更明確一些?
下面咱們用一個實例來感覺一下:正則表達式
import requests r=requests.get('http://httpbin.org/get') print(type(r),r.status_code,type(r.text),r.text,type(r.cookies),r.cookies,sep='\n')
運行結果以下:json
<class 'requests.models.Response'> 200 <class 'str'> { "args": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.21.0" }, "origin": "114.253.118.8, 114.253.118.8", "url": "https://httpbin.org/get" } <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[]>
上面的例子中咱們調用 get() 方法便可實現和 urlopen() 相同的操做,獲得一個 Response 對象,而後分別輸出了 Response 的類型,Status Code,Response Body 的類型、內容還有 Cookies。
經過上述實例能夠發現,它的返回類型是 requests.models.Response,Response Body 的類型是字符串 str,Cookies 的類型是 RequestsCookieJar。
使用了 get() 方法就成功實現了一個 GET 請求,但這倒不算什麼,更方便的在於其餘的請求類型依然能夠用一句話來完成。
用一個實例來感覺一下:segmentfault
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')
在這裏分別用 post()、put()、delete() 等方法實現了 POST、PUT、DELETE 等請求,怎麼樣?是否是比 Urllib 簡單太多了?
其實這只是冰山一角,更多的還在後面。windows
HTTP 中最多見的請求之一就是 GET 請求,咱們首先來詳細瞭解下利用 Requests 來構建 GET 請求的方法以及相關屬性方法操做。瀏覽器
首先讓咱們來構建一個最簡單的 GET 請求,請求的連接爲:http://httpbin.org/get,它會判斷若是若是是 GET 請求的話,會返回響應的 Request 信息。cookie
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.10.0" }, "origin": "122.4.215.33", "url": "http://httpbin.org/get" }
能夠發現咱們成功發起了 GET 請求,返回的結果中包含了 Request Headers、URL、IP 等信息。
那麼 GET 請求,若是要附加額外的信息通常是怎樣來添加?好比如今我想添加兩個參數,名字 name 是 germey,年齡 age 是 22。構造這個請求連接是否是咱們要直接寫成:
r = requests.get('http://httpbin.org/get?name=g...;age=22')
能夠是能夠,可是不以爲很不人性化嗎?通常的這種信息數據咱們會用字典來存儲,那麼怎樣來構造這個連接呢?
一樣很簡單,利用 params 這個參數就行了。
實例以下:
import requests data = { 'name': 'germey', 'age': 22 } r = requests.get("http://httpbin.org/get", params=data) print(r.text)
運行結果以下:
{ "args": { "age": "22", "name": "germey" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Host": "httpbin.org", "User-Agent": "python-requests/2.10.0" }, "origin": "122.4.215.33", "url": "http://httpbin.org/get?age=22&name=germey" }
經過返回信息咱們能夠判斷,請求的連接自動被構形成了:http://httpbin.org/get?age=22...;name=germey。
另外,網頁的返回類型其實是 str 類型,可是它很特殊,是 Json 的格式,因此若是咱們想直接把返回結果解析,獲得一個字典格式的話,能夠直接調用 json() 方法。
用一個實例來感覺一下:
import requests r = requests.get("http://httpbin.org/get") print(type(r.text)) print(r.json()) print(type(r.json()))
運行結果以下:
<class 'str'>
{'headers': {'Accept-Encoding': 'gzip, deflate', 'Accept': '/', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.10.0'}, 'url': 'http://httpbin.org/get', 'args': {}, 'origin': '182.33.248.131'}
<class 'dict'>
能夠發現,調用 json() 方法,就能夠將返回結果是 Json 格式的字符串轉化爲字典。
但注意,若是返回結果不是 Json 格式,便會出現解析錯誤,拋出 json.decoder.JSONDecodeError 的異常。
如上的請求連接返回的是 Json 形式的字符串,那麼若是咱們請求普通的網頁,那麼確定就能得到相應的內容了。
下面咱們以知乎-發現頁面爲例來感覺一下:
import requests import re headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36' } r = requests.get("https://www.zhihu.com/explore", headers=headers) pattern = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S) titles = re.findall(pattern, r.text) print(titles)
如上代碼,咱們請求了知乎-發現頁面:https://www.zhihu.com/explore,在這裏加入了 Headers 信息,其中包含了 User-Agent 字段信息,也就是瀏覽器標識信息。若是不加這個,知乎會禁止抓取。
在接下來用到了最基礎的正則表達式,來匹配出全部的問題內容,關於正則表達式會在後面的章節中詳細介紹,在這裏做爲用到實例來配合講解。
運行結果以下:
['\n如何評價楊超越對偶像意義的理解?\n', '\n中國綠髮會宣稱「穿山甲功能性滅絕」,引起學者質疑後反控對方誹謗,應該相信哪邊?\n', '\n如何科學地解釋MacBook Pro 2019的CPU性能表現接近甚至超過ROG玩家國度槍神3?\n', '\n如何評價楊超越對偶像意義的理解?\n', '\n盛京劍客爲啥退出知乎了?\n', '\n怎麼看我國跆拳道選手鄭姝音被判負後衆人不滿,我國參加相似比賽還有必要麼?\n', '\n你爲何這麼不肯意《極限挑戰》換人?\n', '\n「吉卜力工做室」是一家怎樣的動畫製做公司?\n', '\n你爲何不喜歡張雪迎?\n', '\n《王者榮耀》中,你遇到哪些有意思的隊友?\n']
發現成功提取出了全部的問題內容。
在上面的例子中,咱們抓取的是知乎的一個頁面,實際上它返回的是一個 HTML 文檔,那麼若是咱們想抓去圖片、音頻、視頻等文件的話應該怎麼辦呢?
咱們都知道,圖片、音頻、視頻這些文件都是本質上由二進制碼組成的,因爲有特定的保存格式和對應的解析方式,咱們才能夠看到這些形形色色的多媒體。因此想要抓取他們,那就須要拿到他們的二進制碼。
下面咱們以 GitHub 的站點圖標爲例來感覺一下:
import requests r = requests.get("https://github.com/favicon.ico") print(r.text) print(r.content)
抓取的內容是站點圖標,也就是在瀏覽器每個標籤上顯示的小圖標,如圖 3-3 所示:
圖 3-3 站點圖標
在這裏打印了 Response 對象的兩個屬性,一個是text,另外一個是 content。
運行結果以下,因爲包含特殊內容,在此放運行結果的圖片,如圖 3-4 所示:
圖 3-4 運行結果
那麼前兩行即是 r.text 的結果,最後一行是 r.content 的結果。
能夠注意到,前者出現了亂碼,後者結果前面帶有一個 b,表明這是 bytes 類型的數據。因爲圖片是二進制數據,因此前者在打印時轉化爲 str 類型,也就是圖片直接轉化爲字符串,理所固然會出現亂碼。
兩個屬性有什麼區別?前者返回的是字符串類型,若是返回結果是文本文件,那麼用這種方式直接獲取其內容便可。若是返回結果是圖片、音頻、視頻等文件,Requests 會爲咱們自動解碼成 bytes 類型,即獲取字節流數據。
進一步地,咱們能夠將剛纔提取到的圖片保存下來。
import requests r = requests.get("https://github.com/favicon.ico") with open('favicon.ico', 'wb') as f: f.write(r.content)
在這裏用了 open() 方法,第一個參數是文件名稱,第二個參數表明以二進制寫的形式打開,能夠向文件裏寫入二進制數據,而後保存。
運行結束以後,能夠發如今文件夾中出現了名爲 favicon.ico 的圖標,如圖 3-5所示:
圖 3-5 圖標
一樣的,音頻、視頻文件也能夠用這種方法獲取。
如 urllib.request 同樣,咱們也能夠經過 headers 參數來傳遞頭信息。
好比上面的知乎的例子,若是不傳遞 Headers,就不能正常請求:
import requests r = requests.get("https://www.zhihu.com/explore") print(r.text)
運行結果以下:
<html> <head><title>400 Bad Request</title></head> <body bgcolor="white"> <center><h1>400 Bad Request</h1></center> <hr><center>openresty</center> </body> </html>
但若是加上 Headers 中加上 User-Agent 信息,那就沒問題了:
import requests headers = { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36' } r = requests.get("https://www.zhihu.com/explore", headers=headers) print(r.text)
固然咱們能夠在 headers 這個參數中任意添加其餘的字段信息。
在前面咱們瞭解了最基本的 GET 請求,另一種比較常見的請求方式就是 POST 了,就像模擬表單提交同樣,將一些數據提交到某個連接。
使用 Request 是實現 POST 請求一樣很是簡單。
咱們先用一個實例來感覺一下:
import requests data = {'name': 'germey', 'age': '22'} r = requests.post("http://httpbin.org/post", data=data) print(r.text)
這裏咱們仍是請求:http://httpbin.org/post,它能夠判斷若是請求是 POST 方式,就把相關請求信息輸出出來。
運行結果以下:
{ "args": {}, "data": "", "files": {}, "form": { "age": "22", "name": "germey" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "18", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.10.0" }, "json": null, "origin": "182.33.248.131", "url": "http://httpbin.org/post" }
能夠發現,成功得到了返回結果,返回結果中的 form 部分就是提交的數據,那麼這就證實 POST 請求成功發送了。
發送 Request 以後,獲得的天然就是 Response,在上面的實例中咱們使用了 text 和 content 獲取了 Response 內容,不過還有不少屬性和方法能夠獲取其餘的信息,好比狀態碼 Status Code、Headers、Cookies 等信息。
下面用一個實例來感覺一下:
import requests r = requests.get('http://www.baidu.com') 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)
在這裏分別打印輸出了 status_code 屬性獲得狀態碼, headers 屬性獲得 Response Headers,cookies 屬性獲得 Cookies,url 屬性獲得 URL,history 屬性獲得請求歷史。
運行結果以下:
<class 'int'> 200 <class 'requests.structures.CaseInsensitiveDict'> {'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'Keep-Alive', 'Content-Encoding': 'gzip', 'Content-Type': 'text/html', 'Date': 'Mon, 17 Jun 2019 11:01:04 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:27:32 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18', 'Set-Cookie': 'BDORZ=27315; max-age=86400; domain=.baidu.com; path=/', 'Transfer-Encoding': 'chunked'} <class 'requests.cookies.RequestsCookieJar'> <RequestsCookieJar[<Cookie BDORZ=27315 for .baidu.com/>]> <class 'str'> http://www.baidu.com/ <class 'list'> []
能夠看到,headers 還有 cookies 這兩個屬性獲得的結果分別是 CaseInsensitiveDict 和 RequestsCookieJar 類型。
在這裏 Status Code 經常使用來判斷請求是否成功,Requests 還提供了一個內置的 Status Code 查詢對象 requests.codes。
用一個實例來感覺一下:
import requests r = requests.get('http://www.jianshu.com') exit() if not r.status_code == requests.codes.ok else print('Request Successfully')
在這裏,經過比較返回碼和內置的成功的返回碼是一致的,來保證請求獲得了正常響應,輸出成功請求的消息,不然程序終止,在這裏咱們用 requests.codes.ok 獲得的是成功的狀態碼 200。
那麼確定不能只有 ok 這個條件碼,下面列出了返回碼和相應的查詢條件:
# Informational. 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',), # Redirection. 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 # Client Error. 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',), # Server Error. 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')
好比若是咱們想判斷結果是否是 404 狀態,能夠用 requests.codes.not_found 來比對。
本節咱們瞭解了利用 Requests 模擬最基本的 GET 和 POST 請求的過程,關於更多高級的用法,會在下一節進行講解。