1. 程式人生 > >python3爬蟲(一)requests庫學習

python3爬蟲(一)requests庫學習

前段時間利用零散時間在mooc上跟著嵩天老師學習了python爬蟲的相關知識,於是想把自己的學習經歷寫下來,對爬蟲的相關知識做一個歸納總結,文中如果有錯誤或者是不嚴謹的地方,歡迎指出和交流。


下面我們開始介紹requests庫。

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

一、 requests模組的安裝

首先我們要繼續requests模組的安裝。

1、 pip命令安裝

  • 在windows系統下只需要在命令列輸入命令 pip install requests

    即可安裝。

  • 在 linux 系統下,只需要輸入命令 sudo pip install requests ,即可安裝。

2、下載安裝包安裝

由於pip命令可能安裝失敗所以有時我們要通過下載第三方庫檔案來進行安裝。

在github上的地址為:https://github.com/requests/requests
下載檔案到本地之後,解壓到python安裝目錄。
之後開啟解壓檔案,在此處執行命令列並輸入:python setup.py install 即可。

之後我們測試requests模組是否安裝正確,在互動式環境中輸入 import requests 如果沒有任何報錯,說明requests模組我們已經安裝成功了

二、requests模組的使用方法

1、requests庫的七個主要方法

方法 解釋
requests.request() 構造一個請求,支援以下各種方法
requests.get() 獲取html的主要方法
requests.head() 獲取html頭部資訊的主要方法
requests.post() 向html網頁提交post請求的方法
requests.put() 向html網頁提交put請求的方法
requests.patch() 向html提交區域性修改的請求
requests.delete() 向html提交刪除請求

(1)requests.get()

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

r=requests.get(url,params,**kwargs)
  
  • 1
  • url: 需要爬取的網站地址。
  • params: 翻譯過來就是引數, url中的額外引數,字典或者位元組流格式,可選。
  • **kwargs : 12個控制訪問的引數
    我們先來講講**kwargs:

**kwargs有以下的引數,對於requests.get,其第一個引數被提出來了。

  • params:字典或位元組序列, 作為引數增加到url中,使用這個引數可以把一些鍵值對以?key1=value1&key2=value2的模式增加到url中
    例如:kv = {‘key1: ’ values’, ‘key2’: ‘values’}
    r = requests.request(‘GET’, ‘http:www.python123.io/ws’, params=kw)
  • data:字典,位元組序或檔案物件,重點作為向伺服器提供或提交資源是提交,,作為request的內容,與params不同的是,data提交的資料並不放在url連結裡, 而是放在url連結對應位置的地方作為資料來儲存。,它也可以接受一個字串物件。
  • json:json格式的資料, json合適在相關的html,http相關的web開發中非常常見, 也是http最經常使用的資料格式, 他是作為內容部分可以向伺服器提交。
    例如:kv = {”key1’: ‘value1’}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, json=kv)

  • headers:字典是http的相關語,對應了向某個url訪問時所發起的http的頭i欄位, 可以用這個欄位來定義http的訪問的http頭,可以用來模擬任何我們想模擬的瀏覽器來對url發起訪問。
    例子: hd = {‘user-agent’: ‘Chrome/10’}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, headers=hd)

  • cookies:字典或CookieJar,指的是從http中解析cookie

  • auth:元組,用來支援http認證功能

  • files:字典, 是用來向伺服器傳輸檔案時使用的欄位。
    例子:fs = {‘files’: open(‘data.txt’, ‘rb’)}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, files=fs)

  • timeout: 用於設定超時時間, 單位為秒,當發起一個get請求時可以設定一個timeout時間, 如果在timeout時間內請求內容沒有返回, 將產生一個timeout的異常。

  • proxies:字典, 用來設定訪問代理伺服器。

  • allow_redirects: 開關, 表示是否允許對url進行重定向, 預設為True。

  • stream: 開關, 指是否對獲取內容進行立即下載, 預設為True。

  • verify:開關, 用於認證SSL證書, 預設為True。

  • cert: 用於設定儲存本地SSL證書路徑

這句程式碼是構造一個伺服器請求request,返回一個包含伺服器資源的response物件。

其中response物件有以下屬性:

屬性 說明
r.status_code http請求的返回狀態,若為200則表示請求成功。
r.text http響應內容的字串形式,即返回的頁面內容
r.encoding 從http header 中猜測的相應內容編碼方式
r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.content http響應內容的二進位制形式

舉例說明:

>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>>  r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>> r.encoding='utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h讀</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a>&nbsp;京ICP證030173號&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(以上r.text內容過長,自行刪除了部分,看出編碼效果即可)

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

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

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

try:
    r=requests.get(url,timeout=30)#請求超時時間為30秒
    r.raise_for_status()#如果狀態不是200,則引發異常
    r.encoding=r.apparent_encoding #配置編碼
    return r.text
except:
    return"產生異常" 
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2) request.head()

看程式碼:

 >>> r=requests.head("http://httpbin.org/get")
 >>>r.headers
 {'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'}
 >>>r.text
 ""
  
  • 1
  • 2
  • 3
  • 4
  • 5

(4)requests.post()

1、向url post一個字典:

>>> 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", 
    "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/post"
}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

>>>r=requests.post("http://httpbin.org/post",data='helloworld')
>>>print(r.text)
{
  "args": {}, 
  "data": "helloworld", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "10", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "218.197.153.150", 
  "url": "http://httpbin.org/post"
}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

(5)requests.put()

看程式碼:

>>> 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"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

(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: 控制訪問的引數

三、requests模組的使用例項

1、京東商品資訊的爬取

不需要對頭部做任何修改,即可爬網頁

import requests
url='http://item.jd.com/2967929.html'
try:
    r=requests.get(url,timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[:1000]) #部分資訊
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2、亞馬遜商品資訊的爬取

該網頁中對爬蟲進行的爬取做了限制,因此我們需要偽裝自己為瀏覽器發出的請求。

import requests
url='http://www.amazon.cn/gp/product/B01M8L5Z3Y'
try:
    kv={'user_agent':'Mozilla/5.0'}
    r=requests.get(url,headers=kv)#改變自己的請求資料
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[1000:2000]) #部分資訊
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3、百度搜索關鍵字提交

百度的關鍵字介面:
https://www.baidu.com/s?wd=keyword

import requests
keyword='python'
try:
    kv={'wd':keyword}
    r=requests.get('https://www.baidu.com/s',params=kv)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(len(r.text)) 
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4、網路圖片的爬取

import requests
import os
try:
    url="http://baishi.baidu.com/watch/02167966440907275567.html"#圖片地址
    root="E:/pic/"
    path=root+url.split("/")[-1]
    if not os.path.exists(root): #目錄不存在建立目錄
        os.mkdir(root)
    if not os.path.exists(path): #檔案不存在則下載
        r=requests.get(url)
        f=open(path,"wb")
        f.write(r.content)
        f.close()
        print("檔案下載成功")
    else:
        print("檔案已經存在")
except:
    print("獲取失敗")
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

小結
本文介紹requests庫的基本應用,後面我會記錄怎麼從爬取的內容提取到我們需要的部分。

python3爬蟲(一)requests庫的學習

前段時間利用零散時間在mooc上跟著嵩天老師學習了python爬蟲的相關知識,於是想把自己的學習經歷寫下來,對爬蟲的相關知識做一個歸納總結,文中如果有錯誤或者是不嚴謹的地方,歡迎指出和交流。


下面我們開始介紹requests庫。

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

一、 requests模組的安裝

首先我們要繼續requests模組的安裝。

1、 pip命令安裝

  • 在windows系統下只需要在命令列輸入命令 pip install requests 即可安裝。

  • 在 linux 系統下,只需要輸入命令 sudo pip install requests ,即可安裝。

2、下載安裝包安裝

由於pip命令可能安裝失敗所以有時我們要通過下載第三方庫檔案來進行安裝。

在github上的地址為:https://github.com/requests/requests
下載檔案到本地之後,解壓到python安裝目錄。
之後開啟解壓檔案,在此處執行命令列並輸入:python setup.py install 即可。

之後我們測試requests模組是否安裝正確,在互動式環境中輸入 import requests 如果沒有任何報錯,說明requests模組我們已經安裝成功了

二、requests模組的使用方法

1、requests庫的七個主要方法

方法 解釋
requests.request() 構造一個請求,支援以下各種方法
requests.get() 獲取html的主要方法
requests.head() 獲取html頭部資訊的主要方法
requests.post() 向html網頁提交post請求的方法
requests.put() 向html網頁提交put請求的方法
requests.patch() 向html提交區域性修改的請求
requests.delete() 向html提交刪除請求

(1)requests.get()

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

r=requests.get(url,params,**kwargs)
  
  • 1
  • url: 需要爬取的網站地址。
  • params: 翻譯過來就是引數, url中的額外引數,字典或者位元組流格式,可選。
  • **kwargs : 12個控制訪問的引數
    我們先來講講**kwargs:

**kwargs有以下的引數,對於requests.get,其第一個引數被提出來了。

  • params:字典或位元組序列, 作為引數增加到url中,使用這個引數可以把一些鍵值對以?key1=value1&key2=value2的模式增加到url中
    例如:kv = {‘key1: ’ values’, ‘key2’: ‘values’}
    r = requests.request(‘GET’, ‘http:www.python123.io/ws’, params=kw)
  • data:字典,位元組序或檔案物件,重點作為向伺服器提供或提交資源是提交,,作為request的內容,與params不同的是,data提交的資料並不放在url連結裡, 而是放在url連結對應位置的地方作為資料來儲存。,它也可以接受一個字串物件。
  • json:json格式的資料, json合適在相關的html,http相關的web開發中非常常見, 也是http最經常使用的資料格式, 他是作為內容部分可以向伺服器提交。
    例如:kv = {”key1’: ‘value1’}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, json=kv)

  • headers:字典是http的相關語,對應了向某個url訪問時所發起的http的頭i欄位, 可以用這個欄位來定義http的訪問的http頭,可以用來模擬任何我們想模擬的瀏覽器來對url發起訪問。
    例子: hd = {‘user-agent’: ‘Chrome/10’}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, headers=hd)

  • cookies:字典或CookieJar,指的是從http中解析cookie

  • auth:元組,用來支援http認證功能

  • files:字典, 是用來向伺服器傳輸檔案時使用的欄位。
    例子:fs = {‘files’: open(‘data.txt’, ‘rb’)}
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, files=fs)

  • timeout: 用於設定超時時間, 單位為秒,當發起一個get請求時可以設定一個timeout時間, 如果在timeout時間內請求內容沒有返回, 將產生一個timeout的異常。

  • proxies:字典, 用來設定訪問代理伺服器。

  • allow_redirects: 開關, 表示是否允許對url進行重定向, 預設為True。

  • stream: 開關, 指是否對獲取內容進行立即下載, 預設為True。

  • verify:開關, 用於認證SSL證書, 預設為True。

  • cert: 用於設定儲存本地SSL證書路徑

這句程式碼是構造一個伺服器請求request,返回一個包含伺服器資源的response物件。

其中response物件有以下屬性:

屬性 說明
r.status_code http請求的返回狀態,若為200則表示請求成功。
r.text http響應內容的字串形式,即返回的頁面內容
r.encoding 從http header 中猜測的相應內容編碼方式
r.apparent_encoding 從內容中分析出的響應內容編碼方式(備選編碼方式)
r.content http響應內容的二進位制形式

舉例說明:

>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>>  r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>> r.encoding='utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h讀</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意見反饋</a>&nbsp;京ICP證030173號&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

(以上r.text內容過長,自行刪除了部分,看出編碼效果即可)

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

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

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

try:
    r=requests.get(url,timeout=30)#請求超時時間為30秒
    r.raise_for_status()#如果狀態不是200,則引發異常
    r.encoding=r.apparent_encoding #配置編碼
    return r.text
except:
    return"產生異常" 
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

(2) request.head()

看程式碼:

 >>> r=requests.head("http://httpbin.org/get")
 >>>r.headers
 {'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'}
 >>>r.text
 ""
  
  • 1
  • 2
  • 3
  • 4
  • 5

(4)requests.post()

1、向url post一個字典:

>>> 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", 
    "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/post"
}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

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

>>>r=requests.post("http://httpbin.org/post",data='helloworld')
>>>print(r.text)
{
  "args": {}, 
  "data": "helloworld", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "10", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "218.197.153.150", 
  "url": "http://httpbin.org/post"
}
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

(5)requests.put()

看程式碼:

>>> 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"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

(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: 控制訪問的引數

三、requests模組的使用例項

1、京東商品資訊的爬取

不需要對頭部做任何修改,即可爬網頁

import requests
url='http://item.jd.com/2967929.html'
try:
    r=requests.get(url,timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[:1000]) #部分資訊
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

2、亞馬遜商品資訊的爬取

該網頁中對爬蟲進行的爬取做了限制,因此我們需要偽裝自己為瀏覽器發出的請求。

import requests
url='http://www.amazon.cn/gp/product/B01M8L5Z3Y'
try:
    kv={'user_agent':'Mozilla/5.0'}
    r=requests.get(url,headers=kv)#改變自己的請求資料
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[1000:2000]) #部分資訊
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

3、百度搜索關鍵字提交

百度的關鍵字介面:
https://www.baidu.com/s?wd=keyword

import requests
keyword='python'
try:
    kv={'wd':keyword}
    r=requests.get('https://www.baidu.com/s',params=kv)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(len(r.text)) 
except:
    print("失敗"
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

4、網路圖片的爬取

import requests
import os
try:
    url="http://baishi.baidu.com/watch/02167966440907275567.html"#圖片地址
    root="E:/pic/"
    path=root+url.split("/")[-1]
    if not os.path.exists(root): #目錄不存在建立目錄
        os.mkdir(root)
    if not os.path.exists(path): #檔案不存在則下載
        r=requests.get(url)
        f=open(path,"wb")
        f.write(r.content)
        f.close()
        print("檔案下載成功")
    else:
        print("檔案已經存在")
except:
    print("獲取失敗")
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

小結
本文介紹requests庫的基本應用,後面我會記錄怎麼從爬取的內容提取到我們需要的部分。

前段時間利用零散時間在mooc上跟著嵩天老師學習了python爬蟲的相關知識,於是想把自己的學習經歷寫下來,對爬蟲的相關知識做一個歸納總結,文中如果有錯誤或者是不嚴謹的地方,歡迎指出和交流。

python3爬蟲(一)requests庫的學習