1. 程式人生 > >小白學 Python 爬蟲(17):Requests 基礎使用

小白學 Python 爬蟲(17):Requests 基礎使用

人生苦短,我用 Python

前文傳送門:

小白學 Python 爬蟲(1):開篇

小白學 Python 爬蟲(2):前置準備(一)基本類庫的安裝

小白學 Python 爬蟲(3):前置準備(二)Linux基礎入門

小白學 Python 爬蟲(4):前置準備(三)Docker基礎入門

小白學 Python 爬蟲(5):前置準備(四)資料庫基礎

小白學 Python 爬蟲(6):前置準備(五)爬蟲框架的安裝

小白學 Python 爬蟲(7):HTTP 基礎

小白學 Python 爬蟲(8):網頁基礎

小白學 Python 爬蟲(9):爬蟲基礎

小白學 Python 爬蟲(10):Session 和 Cookies

小白學 Python 爬蟲(11):urllib 基礎使用(一)

小白學 Python 爬蟲(12):urllib 基礎使用(二)

小白學 Python 爬蟲(13):urllib 基礎使用(三)

小白學 Python 爬蟲(14):urllib 基礎使用(四)

小白學 Python 爬蟲(15):urllib 基礎使用(五)

小白學 Python 爬蟲(16):urllib 實戰之爬取妹子圖

引言

在前面的前置準備中,我們安裝了好多第三方的請求庫,如 Request 、 AioHttp 等,不知各位同學還有印象不,沒印象的同學可以翻翻前面的文章。

前面幾篇文章我們大致瞭解了 urllib 的基本用法,其中確實有很多使用不便的地方,如處理 Cookies 或者使用代理訪問的時候,都需要使用 Opener 和 Handler 來處理。

這時,更加強大的 Request 庫的出現就順理成章。有了 Request 庫,我們可以更加簡單方便的使用這些高階操作。

簡介

首先還是各種官方地址敬上:

  • GitHub:https://github.com/requests/requests
  • 官方文件:http://www.python-requests.org
  • 中文文件:http://docs.python-requests.org/zh_CN/latest

這裡列出各種官方文件的目的是希望各位同學能養成查閱官方文件的習慣,畢竟小編也是人,也會犯錯,相比較而言,官方文件的錯誤率會非常低,包括有時候一些疑難問題都能通過官方文件來解決。

各種基礎概念我們已經在介紹 urllib 基礎使用的時候都介紹過了,這裡也就不再多 BB ,直接進入乾貨環節:寫程式碼 。

這裡我們使用的測試地址依然事前面提到過的:https://httpbin.org/ 。

GET 請求

GET 請求是我們最常用的請求,先來了解一下如何使用 Requests 傳送一個 GET 請求。程式碼如下:

import requests

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

結果如下:

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

這裡就不多講了,和前面的 urllib 是一樣的。

如果我們想在 GET 請求中新增請求引數,需要如何新增呢?

import requests

params = {
    'name': 'geekdigging',
    'age': '18'
}

r1 = requests.get('https://httpbin.org/get', params)
print(r1.text)

結果如下:

{
  "args": {
    "age": "18", 
    "name": "geekdigging"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.22.0"
  }, 
  "origin": "116.234.254.11, 116.234.254.11", 
  "url": "https://httpbin.org/get?name=geekdigging&age=18"
}

可以看到,請求的連結被自動構造成了:https://httpbin.org/get?name=geekdigging&age=18 。

值得注意的一點是, r1.text 返回的資料型別是 str 型別,但是實際上是一個 json ,如果想直接將這個 json 轉化成我們可以直接使用的字典格式,可以使用以下方法:

print(type(r1.text))
print(r1.json())
print(type(r.json()))

結果如下:

<class 'str'>
{'args': {'age': '18', 'name': 'geekdigging'}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.22.0'}, 'origin': '116.234.254.11, 116.234.254.11', 'url': 'https://httpbin.org/get?name=geekdigging&age=18'}
<class 'dict'>

新增請求頭:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'referer': 'https://www.geekdigging.com/'
}
r2 = requests.get('https://httpbin.org/get', headers = headers)
print(r2.text)

結果如下:

{
  "args": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Host": "httpbin.org", 
    "Referer": "https://www.geekdigging.com/", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
  }, 
  "origin": "116.234.254.11, 116.234.254.11", 
  "url": "https://httpbin.org/get"
}

與 urllib.request 一樣,我們也是通過 headers 引數來傳遞頭資訊。

如果我們想要抓取一張圖片或者一個視訊這種檔案,可以怎麼做呢?

這些檔案本質上都是由二進位制碼組成的,由於有特定的儲存格式和對應的解析方式,我們才可以看到這些形形色色的多媒體。所以,想要抓取它們,就要拿到它們的二進位制碼。

比如我們抓取一張百度上的 logo 圖片,圖片地址為:https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png

import requests

r3 = requests.get("https://www.baidu.com/img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png")
with open('baidu_logo.png', 'wb') as f:
    f.write(r3.content)

結果小編就不展示了,可以正常下載。

POST 請求

我們接著來介紹一個非常常用的 POST 請求。和上面的 GET 請求一樣,我們依然使用: https://httpbin.org/post 進行測試。示例程式碼如下:

import requests

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
    'referer': 'https://www.geekdigging.com/'
}

params = {
    'name': 'geekdigging',
    'age': '18'
}

r = requests.post('https://httpbin.org/post', data = params, headers = headers)
print(r.text)

結果如下:

{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "age": "18", 
    "name": "geekdigging"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "Referer": "https://www.geekdigging.com/", 
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
  }, 
  "json": null, 
  "origin": "116.234.254.11, 116.234.254.11", 
  "url": "https://httpbin.org/post"
}

我們在這個 POST 請求中添加了請求頭和引數。

Response 響應

上面我們使用過 text 和 json 來獲取響應內容,除了這兩個,還有很多屬性和方法可以用來獲取其他資訊。

我們來訪問百度首頁演示一下:

import requests

r = requests.get('https://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)

結果如下:

<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': 'Thu, 05 Dec 2019 13:24:11 GMT', 'Last-Modified': 'Mon, 23 Jan 2017 13:23:55 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'> https://www.baidu.com/
<class 'list'> []

這裡分別列印輸出 status_code 屬性得到狀態碼,輸出 headers 屬性得到響應頭,輸出 cookies 屬性得到 Cookies ,輸出 url 屬性得到 URL ,輸出 history 屬性得到請求歷史。

示例程式碼

本系列的所有程式碼小編都會放在程式碼管理倉庫 Github 和 Gitee 上,方便大家取用。

示例程式碼-Github

示例程式碼-Gi