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庫的基本應用,後面我會記錄怎麼從爬取的內容提取到我們需要的部分。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章