爬蟲—使用Requests

一,安裝

  pip install requestscss

二,基本用法

1.簡單示例

import requests

res = requests.get('https://www.baidu.com')
print(type(res))
print(res.status_code)
print(res.text)
print(type(res.text))
print(res.cookies)

運行結果:html

<class 'requests.models.Response'>
200
<!DOCTYPE html>
<!--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 content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</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>

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

  經過運行結果可發現,它返回的類型是requests.models.Response,響應體字符串類型是str,Cookie的類型是RequestsCookieJar。python

2.GET請求

  這裏使用httpbin測試接口進行測試,httpbin這個網站能測試 HTTP 請求和響應的各類信息,好比 cookie、ip、headers 和登陸驗證等,且支持 GET、POST 等多種方法,對 web 開發和測試頗有幫助。它由 Python + Flask 編寫,是一個開源項目(官方網站:http://httpbin.org/開源地址:https://github.com/Runscope/httpbin)。  git

# GET請求
res = requests.get('https://httpbin.org/get')
print(res.text)

運行結果:github

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/get"
}

  能夠發現,咱們成功的發起了GET請求,返回的結果中包含請求頭,URL,IP等信息。web

♦傳遞參數

  對於GET請求,如何添加參數呢?好比name是rain,age是22。是否是須要寫成:正則表達式

  res = requests.get('https://httpbin.org/get?name=rain&age=22')json

  其實這樣也能夠,可是這種數據信息通常使用字典來存儲。瀏覽器

# 帶參數
data = {
    'name': 'rain',
    'age': 22
}
res = requests.get('https://httpbin.org/get',params=data)
print(res.text)

  運行結果:cookie

{
  "args": {
    "age": "22", 
    "name": "rain"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/get?name=rain&age=22"
}

  能夠看到,請求的鏈接被自動構形成了:https://httpbin.org/get?name=rain&age=22。

  須要注意的是網頁返回的類型其實是str類型,但其格式爲JSON字符串,想要解析結果,得到一個字典類型的話,能夠直接調用json()方法:

# 轉成字典
print(type(res.json()))

結果:
<class 'dict'>

  若是返回的類型不是JSON類型,此時調用json()方法,就會拋出json.decoder.JSONDecoderError異常。

♦抓取網頁

  若是請求普通的網頁,就能得到相應的內容。下面以「知乎「的」發現「頁面爲例:

# 抓取網頁,發現—知乎
import requests
import re

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36"
}
res = requests.get('https://www.zhihu.com/explore', headers=headers)
parse = re.compile('explore-feed.*?question_link.*?>(.*?)</a>', re.S)
text = re.findall(parse,res.text)
print(text)

  這裏咱們加入了,headers信息,也就是user-agent字段信息,也就是瀏覽器標識。若是不加上這個,就會被禁止抓取。以後使用正則表達式匹配出a節點裏面的問題內容。結果以下:

['\n如今的復古8-bit風格遊戲和當時真正的8-bit遊戲有哪些差異?\n', '\n如何評價羅雲熙在《白髮》中飾演的容齊?\n', '\n爲何要把敦煌莫高窟建在西北地區?\n', '\n貓的哪些行爲會讓你以爲貓是愛你的?\n', '\n老人老是經過騙孩子的方式讓孩子服從本身的命令,這種狀況怎麼辦?\n', '\n如何看待faker在直播中說白銀怎麼喜歡閃現放D?\n', '\n有哪些女演員在影視劇中的扮相讓你驚豔?\n', '\nPowerPoint 到底有多厲害?\n', '\n如何評價華晨宇?\n', '\n毛細現象水液麪是否是球面的一部分?\n']
♦抓取二進制數據

  瀏覽網頁時,咱們常常看到頁面中會有圖片,音頻,視頻等文件。這些文件本質上由二進制碼組成的,使用了特定的保存格式和對應的解析方式,咱們才得以看到這些形形色色的多媒體。想要抓取他們,就須要拿到其二進制碼。

  以GitHub站點的圖標爲例:

# 抓取二進制文件
res = requests.get('https://github.com/favicon.ico')
print(res.text)
print(res.content)

  這裏抓取的是站點圖標,就是瀏覽器每個標籤上顯示的小圖標,以下圖:

                                   

  這裏打印了text和content,結果以下:

                                                                        +++G��������G+++                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
b'\x00\x00\x01\x00\x02\x00\x10\x10\x00\x00\x01\x00 \x00(\x05\x00\x00&\x00\x00\x00  \x00\x00\x01\x00 \x00(\x14\x00\x00N\x05\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00 

  能夠看到前者出現了亂碼,後者開頭帶上了一個b,說明是bytes類型。因爲是二進制數據,全部text打印時轉化成str類型,圖片直接轉化爲字符串,天然就會出現亂碼。接下來,咱們將圖片保存下來:

res = requests.get('https://github.com/favicon.ico')
with open('favicon.ico','wb') as f:
    f.write(res.content)

  使用open()方法以二進制寫的形式打開文件,向文件裏寫入二進制數據。以後咱們打開剛纔寫入的文件:

                           

  這裏能夠看到,成功的獲取到了網頁上面的圖標信息,一樣的音頻和視頻也可使用這種方法來獲取。

 

 3.POST請求

  使用requests發送POST請求也一樣簡單:

# POST請求
data = {
    'name':'rain',
    'age':'22'
}
res = requests.post('https://httpbin.org/post',data=data)
print(res.text)

  運行結果:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "22", 
    "name": "rain"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "16", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "183.129.61.183, 183.129.61.183", 
  "url": "https://httpbin.org/post"
}

  能夠看到,咱們成功的獲取了返回結果,其中form裏面的數據就是提交的數據,也證實了POST請求成功。

4.響應信息

  發送請求成功後,獲得的天然是相應。上面的例子中,咱們使用text和content獲取了響應的內容。此外還有不少方法能夠用來獲取響應的其餘信息:

# 獲取響應信息
res = requests.get('http://www.baidu.com')
print(type(res.status_code), res.status_code)   # 響應狀態碼
print(type(res.headers), res.headers)           # 響應頭信息
print(type(res.cookies), res.cookies)           # Cookies信息
print(type(res.url), res.url)                   # 請求url
print(type(res.history), res.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': 'Fri, 24 May 2019 10:02:25 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:28:37 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'> []

  其中響應狀態碼常常用來判斷請求是否成功,而requests還提供了一個內置的狀態碼查詢對象requests.codes:

# requests內置狀態碼查詢
res = requests.get('http://www.baidu.com')
exit() if not res.status_code == requests.codes.ok else print("Request Successful!")

  運行結果:

Request Successful!

  這裏經過響應信息中的請求成功狀態碼與requests內置請求成功狀態碼進行比較來判斷請求是否成功。其中requests.codes.ok的值爲200。

相關文章
相關標籤/搜索