Requests 快速指南



Requests - 概述

Requests 是一個 HTTP 庫,它提供了易於使用的功能來處理 Web 應用程式中的 HTTP 請求/響應。該庫是用 Python 開發的。

Python Requests 的官方網站位於 https://2.python-requests.org/en/master/,其定義如下:

Requests 是一個優雅而簡單的 Python HTTP 庫,專為人類而設計。

Requests 的特性

下面將討論 Requests 的特性:

請求

Python Requests 庫提供了易於使用的處理 HTTP 請求的方法。傳遞引數和處理請求型別(如 GET、POST、PUT、DELETE 等)非常簡單。

響應

您可以根據需要獲取響應,支援的格式包括文字格式、二進位制響應、JSON 響應和原始響應。

頭資訊

該庫允許您根據需要讀取、更新或傳送新的頭資訊。

超時

您可以使用 Python Requests 庫輕鬆地為要請求的 URL 新增超時。例如,您正在使用第三方 URL 並等待響應。

始終建議為 URL 設定超時,因為我們可能希望 URL 在超時時間內以響應或因超時導致的錯誤進行響應。否則可能會導致無限期地等待該請求。

錯誤處理

Requests 模組支援錯誤處理,其中一些錯誤包括連線錯誤、超時錯誤、TooManyRedirects、Response.raise_for_status 錯誤等。

Cookie

該庫允許您讀取、寫入和更新請求 URL 的 Cookie。

會話

為了在請求之間維護資料,您需要使用會話。因此,如果反覆呼叫同一個主機,您可以重用 TCP 連線,從而提高效能。

SSL 證書

SSL 證書是安全 URL 的一項安全功能。當您使用 Requests 時,它還會驗證提供的 HTTPS URL 的 SSL 證書。Requests 庫預設啟用 SSL 驗證,如果證書不存在,則會丟擲錯誤。

身份驗證

HTTP 身份驗證是在伺服器端,當客戶端請求 URL 時,要求提供一些身份驗證資訊,例如使用者名稱和密碼。這是對客戶端和伺服器之間交換的請求和響應的額外安全措施。

使用 Python Requests 庫的優勢

以下是使用 Python Requests 庫的優勢:

  • 易於使用並從給定的 URL 獲取資料。

  • Requests 庫可用於從網站抓取資料。

  • 使用 Requests,您可以獲取、釋出、刪除和更新給定 URL 的資料。

  • Cookie 和會話的處理非常簡單。

  • 藉助身份驗證模組的支援,也確保了安全性。

Requests - 環境設定

在本章中,我們將學習 Requests 的安裝。要開始使用 Requests 模組,我們需要先安裝 Python。因此,我們將執行以下操作:

  • 安裝 Python
  • 安裝 Requests

安裝 Python

訪問 Python 官方網站:https://python.club.tw/downloads/(如下所示),並點選適用於 Windows、Linux/Unix 和 Mac OS 的最新版本。根據您的 64 位或 32 位作業系統下載 Python。

Python Download

下載完成後,點選 .exe 檔案並按照步驟在您的系統上安裝 Python。

Python For Windows

Python 包管理器 pip 會在上述安裝過程中預設安裝。為了使其在您的系統上全域性生效,請將 Python 的路徑直接新增到 PATH 環境變數中。在安裝開始時會顯示相同的提示,請務必選中“新增到 PATH”複選框。如果您忘記選中它,請按照以下步驟將其新增到 PATH。

要新增到 PATH,請按照以下步驟操作:

右鍵點選“此電腦”圖示,然後點選“屬性”>“高階系統設定”。

將顯示如下螢幕:

System properties

點選“環境變數”,將顯示如下螢幕:

Environment Variables

選擇“Path”並點選“編輯”按鈕,在末尾新增 Python 的路徑。現在,讓我們檢查 Python 版本。

檢查 Python 版本

E:\prequests>python --version
Python 3.7.3

安裝 Requests

現在我們已經安裝了 Python,接下來我們將安裝 Requests。

安裝 Python 後,Python 包管理器 pip 也會安裝。以下是檢查 pip 版本的命令。

E:\prequests>pip --version
pip 19.1.1 from c:\users\xxxxx\appdata\local\programs\python\python37\lib\site-p
ackages\pip (python 3.7)

我們已經安裝了 pip,版本為 19.1.1。現在,我們將使用 pip 安裝 Requests 模組。

命令如下:

pip install requests
E:\prequests>pip install requests
Requirement already satisfied: requests in c:\users\xxxx\appdata\local\programs
\python\python37\lib\site-packages (2.22.0)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\kamat\appdata\loca
l\programs\python\python37\lib\site-packages (from requests) (2019.3.9)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\use
rs\xxxxx\appdata\local\programs\python\python37\lib\site-packages (from requests
) (1.25.3)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\xxxxxxx\appdata\local\pr
ograms\python\python37\lib\site-packages (from requests) (2.8)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\xxxxx\appdata\l
ocal\programs\python\python37\lib\site-packages (from requests) (3.0.4)

我們已經安裝了該模組,因此在命令提示符中顯示“Requirement already satisfied”;如果未安裝,它將下載安裝所需的軟體包。

要檢查已安裝的 Requests 模組的詳細資訊,可以使用以下命令:

pip show requests
E:\prequests>pip show requests
Name: requests
Version: 2.22.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
License: Apache 2.0
Location: c:\users\xxxxx\appdata\local\programs\python\python37\lib\site-package
S
Requires: certifi, idna, urllib3, chardet
Required-by:

Requests 模組的版本為 2.22.0。

Requests - HTTP 請求是如何工作的?

Python 的 Requests 是一個 HTTP 庫,它將幫助我們在客戶端和伺服器之間交換資料。假設您有一個帶有表單的 UI,您需要在其中輸入使用者詳細資訊,那麼一旦輸入完成後,您需要提交資料,這實際上是客戶端向伺服器傳送的 HTTP POST 或 PUT 請求,以儲存資料。

當您需要資料時,您需要從伺服器獲取它,這又是一個 HTTP GET 請求。客戶端請求資料時以及伺服器以所需資料響應之間的這種資料交換,客戶端和伺服器之間的這種關係非常重要。

請求傳送到給定的 URL,該 URL 可以是安全或非安全 URL。

可以使用 GET、POST、PUT、DELETE 方法向 URL 傳送請求。最常用的方法是 GET 方法,主要用於從伺服器獲取資料。

您還可以將資料作為查詢字串傳送到 URL,例如:

https://jsonplaceholder.typicode.com/users?id=9&username=Delphine

因此,這裡我們將 id=9 和 username=Delphine 傳遞給 URL。所有值都在問號 (?) 後以鍵值對的形式傳送,多個引數透過 & 分隔傳遞給 URL。

使用 Requests 庫,可以使用字串字典如下呼叫 URL。

其中,資料以字串字典的形式傳送到 URL。如果要傳遞 id=9 和 username=Delphine,可以執行以下操作:

payload = {'id': '9', 'username': 'Delphine'}

Requests 庫的呼叫方式如下:

res = requests.get('https://jsonplaceholder.typicode.com/users', params=payload')

使用 POST,我們可以執行以下操作:

res = requests.post('https://jsonplaceholder.typicode.com/users', data = {'id':'9', 'username':'Delphine'})

使用 PUT

res = requests.put('https://jsonplaceholder.typicode.com/users', data = {'id':'9', 'username':'Delphine'})

使用 DELETE

res = requests.delete('https://jsonplaceholder.typicode.com/users')

HTTP 請求的響應可以是文字編碼形式、二進位制編碼、JSON 格式或原始響應。請求和響應的詳細資訊將在後續章節中詳細解釋。

Requests - 使用 Requests

在本章中,我們將瞭解如何使用 Requests 模組。我們將研究以下內容:

  • 發出 HTTP 請求。
  • 向 HTTP 請求傳遞引數。

發出 HTTP 請求

要發出 HTTP 請求,我們需要首先匯入 Requests 模組,如下所示:

import requests 

現在讓我們看看如何使用 Requests 模組呼叫 URL。

讓我們在程式碼中使用 URL https://jsonplaceholder.typicode.com/users 來測試 Requests 模組。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.status_code)

使用 requests.get() 方法呼叫 URL https://jsonplaceholder.typicode.com/users。URL 的響應物件儲存在 getdata 變數中。當我們列印變數時,它會給出 200 響應程式碼,這意味著我們已成功獲取響應。

輸出

E:\prequests>python makeRequest.py
<Response [200]>

要從響應中獲取內容,可以使用 getdata.content,如下所示:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.content)

getdata.content 將列印響應中所有可用的資料。

輸出

E:\prequests>python makeRequest.py
b'[\n {\n  "id": 1,\n  "name": "Leanne Graham",\n  "username": "Bret",\n
"email": "Sincere@april.biz",\n  "address": {\n  "street": "Kulas Light
",\n  "suite": "Apt. 556",\n  "city": "Gwenborough",\n  "zipcode": "
92998-3874",\n  "geo": {\n "lat": "-37.3159",\n  "lng": "81.149
6"\n }\n },\n  "phone": "1-770-736-8031 x56442",\n  "website": "hild
egard.org",\n  "company": {\n "name": "Romaguera-Crona",\n  "catchPhr
ase": "Multi-layered client-server neural-net",\n  "bs": "harness real-time
e-markets"\n }\n }

向 HTTP 請求傳遞引數

僅請求 URL 是不夠的,我們還需要向 URL 傳遞引數。

引數通常以鍵值對的形式傳遞,例如:

 https://jsonplaceholder.typicode.com/users?id=9&username=Delphine

因此,我們有 id=9 和 username=Delphine。現在,我們將瞭解如何將此類資料傳遞給 Requests HTTP 模組。

示例

import requests
payload = {'id': 9, 'username': 'Delphine'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users', params=payload)
print(getdata.content)

詳細資訊儲存在物件 payload 的鍵值對中,並傳遞給 get() 方法中的 params。

輸出

E:\prequests>python makeRequest.py
b'[\n {\n "id": 9,\n "name": "Glenna Reichert",\n "username": "Delphin
e",\n "email": "Chaim_McDermott@dana.io",\n "address": {\n "street":
"Dayna Park",\n "suite": "Suite 449",\n "city": "Bartholomebury",\n
"zipcode": "76495-3109",\n "geo": {\n "lat": "24.6463",\n
"lng": "-168.8889"\n }\n },\n "phone": "(775)976-6794 x41206",\n "
website": "conrad.com",\n "company": {\n "name": "Yost and Sons",\n
"catchPhrase": "Switchable contextually-based project",\n "bs": "aggregate
real-time technologies"\n }\n }\n]'

我們現在在響應中獲取了 id=9 和 username=Delphine 的詳細資訊。

如果您想檢視傳遞引數後 URL 的外觀,可以使用響應物件到 URL。

示例

import requests
payload = {'id': 9, 'username': 'Delphine'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users', params=payload)
print(getdata.url)

輸出

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users?id=9&username=Delphine

處理 HTTP 請求的響應

在本章中,我們將深入瞭解從 Requests 模組接收到的響應的更多細節。我們將討論以下內容:

  • 獲取響應
  • JSON 響應
  • 原始響應
  • 二進位制響應

獲取響應

我們將使用 request.get() 方法向 URL 發出請求。

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users');    

getdata 函式擁有 response 物件。它包含響應的所有詳細資訊。我們可以使用 (.text) 和 (.content) 以兩種方式獲取響應。使用 response.text 將以文字格式返回資料,如下所示:

示例

E:\prequests>python makeRequest.py
[
 {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
   "bs": "harness real-time e-markets"
  }
},

您會看到響應與在瀏覽器中檢視 URL 原始碼時顯示的相同,如下所示:

Typicode

您也可以嘗試 .html URL 並使用 response.text 檢視內容,它將與瀏覽器中 .html URL 的原始碼內容相同。

現在,讓我們嘗試對同一個 URL 使用 response.content 並檢視輸出。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.content)

輸出

E:\prequests>python makeRequest.py
b'[\n {\n "id": 1,\n "name": "Leanne Graham",\n "username": "Bret",\n
"email": "Sincere@april.biz",\n "address": {\n "street": "Kulas Light
",\n "suite": "Apt. 556",\n "city": "Gwenborough",\n "zipcode": "
92998-3874",\n "geo": {\n "lat": "-37.3159",\n "lng": "81.149
6"\n }\n },\n "phone": "1-770-736-8031 x56442",\n "website": "hild
egard.org",\n "company": {\n "name": "Romaguera-Crona",\n "catchPhr
ase": "Multi-layered client-server neural-net",\n "bs": "harness real-time
e-markets"\n }\n },\n {\n "id": 2,\n "name": "Ervin Howell",\n "us
ername": "Antonette",\n "email": "Shanna@melissa.tv",\n "address": {\n
"street": "Victor Plains",\n "suite": "Suite 879",\n "city": "Wisoky
burgh",\n "zipcode": "90566-7771",\n "geo": {\n "lat": "-43.950
9",\n "lng": "-34.4618"\n }\n },\n "phone": "010-692-6593 x091
25",\n "website": "anastasia.net",\n "company": {\n "name": "Deckow-C
rist",\n "catchPhrase": "Proactive didactic contingency",\n "bs": "syn
ergize scalable supply-chains"\n }\n },\n {\n "id": 3,\n "name": "Cle
mentine Bauch",\n "username": "Samantha",\n "email":
"Nathan@yesenia.net",
\n "address": {\n "street": "Douglas Extension",\n "suite": "Suite
847",\n "city": "McKenziehaven",\n "zipcode": "59590-4157",\n "ge
o": {\n "lat": "-68.6102",\n "lng": "-47.0653"\n }\n },\n

響應以位元組形式給出。您將在響應的開頭看到字母b。使用 requests 模組,您可以獲取使用的編碼,並在需要時更改編碼。例如,要獲取編碼,您可以使用 response.encoding。

print(getdata.encoding)

輸出

utf-8

您可以按如下方式更改編碼:您可以使用您選擇的編碼。

getdata.encoding = 'ISO-8859-1'

JSON 響應

您還可以透過使用 response.json() 方法以 json 格式獲取 Http 請求的響應,如下所示:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.json())

輸出

E:\prequests>python makeRequest.py
[{'id': 1, 'name': 'Leanne Graham', 'username': 'Bret', 'email': 'Sincere@april.
biz', 'address': {'street': 'Kulas Light', 'suite': 'Apt. 556', 'city': 'Gwenbor
ough', 'zipcode': '92998-3874', 'geo': {'lat': '-37.3159', 'lng': '81.1496'}},
'
phone': '1-770-736-8031 x56442', 'website': 'hildegard.org', 'company': {'name':
'Romaguera-Crona', 'catchPhrase': 'Multi-layered client-server neural-net', 'bs
': 'harness real-time e-markets'}}]

原始響應

如果您需要 Http URL 的原始響應,您可以使用 response.raw,並在 get 方法中新增stream=True,如下所示:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users', stream=True)
print(getdata.raw)

輸出

E:\prequests>python makeRequest.py
<urllib3.response.HTTPResponse object at 0x000000A8833D7B70>

要從原始資料中讀取更多內容,您可以按如下方式操作:

print(getdata.raw.read(50))

輸出

E:\prequests>python makeRequest.py
b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x95\x98[o\xe38\x12\x85\xdf\xe7W\x10y\
xda\x01F\x82.\xd4m\x9f\xdc\x9dd\xba\xb7\x93\xf4\x06q\xef4\x06\x83A@K\x15\x89m'

二進位制響應

要獲取二進位制響應,我們可以使用 response.content。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.content)

輸出

E:\prequests>python makeRequest.py
b'[\n {\n "id": 1,\n "name": "Leanne Graham",\n "username": "Bret",\n
"email": "Sincere@april.biz",\n "address": {\n "street": "Kulas Light
",\n "suite": "Apt. 556",\n "city": "Gwenborough",\n "zipcode": "
92998-3874",\n "geo": {\n "lat": "-37.3159",\n "lng": "81.149
6"\n }\n },\n "phone": "1-770-736-8031 x56442",\n "website": "hild
egard.org",\n "company": {\n "name": "Romaguera-Crona",\n "catchPhr
ase": "Multi-layered client-server neural-net",\n "bs": "harness real-time
e-markets"\n }\n },\n {\n "id": 2,\n "name": "Ervin Howell",\n "us
ername": "Antonette",\n "email": "Shanna@melissa.tv",\n "address": {\n
"street": "Victor Plains",\n "suite": "Suite 879",\n "city": "Wisoky
burgh",\n "zipcode": "90566-7771",\n "geo": {\n "lat": "-43.950
9",\n "lng": "-34.4618"\n }\n },\n "phone": "010-692-6593 x091
25",\n "website": "anastasia.net",\n "company": {\n "name": "Deckow-C
rist",\n "catchPhrase": "Proactive didactic contingency",\n "bs": "syn
ergize scalable supply-chains"\n }\n },\n {\n "id": 3,\n "name": "Cle
mentine Bauch",\n "username": "Samantha",\n "email": "Nathan@yesenia.net",
\n "address": {\n "street": "Douglas Extension",\n "suite": "Suite
847",\n "city": "McKenziehaven",\n "zipcode": "59590-4157",\n "ge
o": {\n "lat": "-68.6102",\n "lng": "-47.0653"\n }\n },\n

響應以位元組形式給出。您將在響應的開頭看到字母b。二進位制響應主要用於非文字請求。

Requests - HTTP 請求頭

在上一章中,我們已經瞭解瞭如何發出請求並獲取響應。本章將進一步探討 URL 的標頭部分。因此,我們將研究以下內容:

  • 理解請求標頭
  • 自定義標頭
  • 響應標頭

理解請求標頭

在瀏覽器中點選任意 URL,檢查它並在開發者工具的網路選項卡中檢視。

您將獲得響應標頭、請求標頭、有效負載等。

例如,請考慮以下 URL:

https://jsonplaceholder.typicode.com/users

View Source

您可以按如下方式獲取標頭詳細資訊:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users', stream=True)
print(getdata.headers)

輸出

E:\prequests>python makeRequest.py
{'Date': 'Sat, 30 Nov 2019 05:15:00 GMT', 'Content-Type': 'application/json; cha
rset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Co
okie': '__cfduid=d2b84ccf43c40e18b95122b0b49f5cf091575090900; expires=Mon, 30-De
c-19 05:15:00 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 'Exp
ress', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't
rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '
X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ
"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'A
ge': '2271', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudf
lare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53da574f
f99fc331-SIN'}

要讀取任何 http 標頭,您可以按如下方式操作:

getdata.headers["Content-Encoding"] // gzip

自定義標頭

您還可以將標頭髮送到正在呼叫的 URL,如下所示。

示例

import requests
headers = {'x-user': 'test123'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users', headers=headers)

傳遞的標頭必須是字串、位元組字串或 Unicode 格式。請求的行為不會根據傳遞的自定義標頭而改變。

響應標頭

當您在瀏覽器開發者工具的網路選項卡中檢查 URL 時,響應標頭如下所示:

View Sourcecode

要從 requests 模組獲取標頭的詳細資訊,請使用 Response.headers,如下所示:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.headers)

輸出

E:\prequests>python makeRequest.py
{'Date': 'Sat, 30 Nov 2019 06:08:10 GMT', 'Content-Type': 'application/json; cha
rset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Set-Co
okie': '__cfduid=de1158f1a5116f3754c2c353055694e0d1575094090; expires=Mon, 30-De
c-19 06:08:10 GMT; path=/; domain=.typicode.com; HttpOnly', 'X-Powered-By': 'Exp
ress', 'Vary': 'Origin, Accept-Encoding', 'Access-Control-Allow-Credentials': 't
rue', 'Cache-Control': 'max-age=14400', 'Pragma': 'no-cache', 'Expires': '-1', '
X-Content-Type-Options': 'nosniff', 'Etag': 'W/"160d-1eMSsxeJRfnVLRBmYJSbCiJZ1qQ
"', 'Content-Encoding': 'gzip', 'Via': '1.1 vegur', 'CF-Cache-Status': 'HIT', 'A
ge': '5461', 'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudf
lare.com/cdn-cgi/beacon/expect-ct"', 'Server': 'cloudflare', 'CF-RAY': '53daa52f
3b7ec395-SIN'}

您可以按如下方式獲取任何所需的特定標頭:

print(getdata.headers["Expect-CT"])

輸出

max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp
ect-ct

您還可以使用 get() 方法獲取標頭詳細資訊。

print(getdata.headers.get("Expect-CT"))

輸出

max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/exp
ect-ct

Requests - 處理 GET 請求

本章將重點關注 GET 請求,它是最常見且使用頻率最高的請求。GET 在 requests 模組中的工作原理非常簡單。以下是一個關於使用 GET 方法處理 URL 的簡單示例。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.content)
getdata.content, will print all the data available in the response.   

輸出

E:\prequests>python makeRequest.py
b'[\n {\n "id": 1,\n "name": "Leanne Graham",\n "username": "Bret",\n
"email": "Sincere@april.biz",\n "address": {\n "street": "Kulas Light
",\n "suite": "Apt. 556",\n "city": "Gwenborough",\n "zipcode": "
92998-3874",\n "geo": {\n "lat": "-37.3159",\n "lng": "81.149
6"\n }\n },\n "phone": "1-770-736-8031 x56442",\n "website": "hild
egard.org",\n "company": {\n "name": "Romaguera-Crona",\n "catchPhr
ase": "Multi-layered client-server neural-net",\n "bs": "harness real-time
e-markets"\n }\n }

您還可以使用 param 屬性將引數傳遞給 get 方法,如下所示:

import requests
payload = {'id': 9, 'username': 'Delphine'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users',
params=payload)
print(getdata.content)

詳細資訊儲存在物件 payload 的鍵值對中,並傳遞給 get() 方法中的 params。

輸出

E:\prequests>python makeRequest.py
b'[\n {\n "id": 9,\n "name": "Glenna Reichert",\n "username": "Delphin
e",\n "email": "Chaim_McDermott@dana.io",\n "address": {\n "street":
"Dayna Park",\n "suite": "Suite 449",\n "city": "Bartholomebury",\n
"zipcode": "76495-3109",\n "geo": {\n "lat": "24.6463",\n
"lng": "-168.8889"\n }\n },\n "phone": "(775)976-6794 x41206",\n "
website": "conrad.com",\n "company": {\n "name": "Yost and Sons",\n
"catchPhrase": "Switchable contextually-based project",\n "bs": "aggregate
real-time technologies"\n }\n }\n]'

處理 POST、PUT、PATCH 和 DELETE 請求

在本章中,我們將瞭解如何使用 requests 庫使用 POST 方法,以及如何將引數傳遞給 URL。

使用 POST

對於 PUT 請求,Requests 庫具有 requests.post() 方法,其示例如下所示

import requests

myurl = 'https://postman-echo.com/post'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.post(myurl, data=myparams)
print(res.text)

輸出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},"headers":{"x-forwarded-proto":"https","host":"postman-echo.com","content-length":"30","accept":"*/*","accept-encoding":"gzip,deflate","content-type":"application/x-www-form-urlencoded","user-agent":"python-requests/2.22.0","x-forwarded-port":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},"url":"https://postman-echo.com/post"}

在上面顯示的示例中,您可以將表單資料作為鍵值對傳遞到 requests.post() 中的 data 引數。我們還將瞭解如何在 requests 模組中使用 PUT、PATCH 和 DELETE。

使用 PUT

對於 PUT 請求,Requests 庫具有 requests.put() 方法,其示例如下所示。

import requests
myurl = 'https://postman-echo.com/put'
myparams = {'name': 'ABC', 'email':'xyz@gmail.com'}
res = requests.put(myurl, data=myparams)
print(res.text)

輸出

E:\prequests>python makeRequest.py
{"args":{},"data":"","files":{},"form":{"name":"ABC","email":"xyz@gmail.com"},"h
eaders":{"x-forwarded-proto":"https","host":"postman-echo.com","content-length":
"30","accept":"*/*","accept-encoding":"gzip, deflate","content-type":"applicatio
n/x-www-form-urlencoded","user-agent":"python-requests/2.22.0","x-forwarded-port
":"443"},"json":{"name":"ABC","email":"xyz@gmail.com"},"url":"https://postman-ec
ho.com/put"}

使用 PATCH

對於 PATCH 請求,Requests 庫具有 requests.patch() 方法,其示例如下所示。

import requests
myurl = https://postman-echo.com/patch'
res = requests.patch(myurl, data="testing patch")
print(res.text)

輸出

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https"
,"host":"postman-echo.com","content-length":"13","accept":"*/*","accept-encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-port":"443"
},"json":null,"url":"https://postman-echo.com/patch"}

使用 DELETE

對於 DELETE 請求,Requests 庫具有 requests.delete() 方法,其示例如下所示。

import requests
myurl = 'https://postman-echo.com/delete'
res = requests.delete(myurl, data="testing delete")
print(res.text)

輸出

E:\prequests>python makeRequest.py
{"args":{},"data":{},"files":{},"form":{},"headers":{"x-forwarded-proto":"https"
,"host":"postman-echo.com","content-length":"14","accept":"*/*","accept-encoding
":"gzip, deflate","user-agent":"python-requests/2.22.0","x-forwarded-port":"443"
},"json":null,"url":"https://postman-echo.com/delete"}

Requests - 檔案上傳

在本章中,我們將使用 request 上傳檔案並讀取上傳的檔案內容。我們可以使用files 引數來實現,如下面的示例所示。

我們將使用http://httpbin.org/post 來上傳檔案。

示例

import requests
myurl = 'https://httpbin.org/post'
files = {'file': open('test.txt', 'rb')}
getdata = requests.post(myurl, files=files)
print(getdata.text)  

Test.txt

File upload test using Requests

示例

var total = [0, 1, 2, 3].reduceRight(function(a, b){ return a + b; }); 
console.log("total is : " + total );    

輸出

E:\prequests>python makeRequest.py
{
  "args": {},
  "data": "",
  "files": {
   "file": "File upload test using Requests"
  },
  "form": {},
  "headers": {
   "Accept": "*/*",
   "Accept-Encoding": "gzip, deflate",
   "Content-Length": "175",
   "Content-Type": "multipart/form-data; 
boundary=28aee3a9d15a3571fb80d4d2a94bf
d33",
   "Host": "httpbin.org",
   "User-Agent": "python-requests/2.22.0"
  },
  "json": null,
  "origin": "117.223.63.135, 117.223.63.135",
  "url": "https://httpbin.org/post"
}

也可以按如下方式傳送檔案內容:

示例

import requests
myurl = 'https://httpbin.org/post'
files = {'file': ('test1.txt', 'Welcome to TutorialsPoint')}
getdata = requests.post(myurl, files=files)
print(getdata.text)

輸出

E:\prequests>python makeRequest.py
{
  "args": {},
  "data": "",
  "files": {
   "file": "Welcome to TutorialsPoint"
},
"form": {},
"headers": {
   "Accept": "*/*",
   "Accept-Encoding": "gzip, deflate",
   "Content-Length": "170",
   "Content-Type": "multipart/form-data; boundary=f2837238286fe40e32080aa7e172b
e4f",
  "Host": "httpbin.org",
  "User-Agent": "python-requests/2.22.0"
},
  "json": null,
  "origin": "117.223.63.135, 117.223.63.135",
  "url": "https://httpbin.org/post"
}

Requests - 使用 Cookie

本章將討論如何處理使用 Http 請求庫時出現的錯誤。始終建議對所有可能的情況進行錯誤管理。

URL https://jsonplaceholder.typicode.com/users 在瀏覽器中訪問時,我們可以獲取 cookie 的詳細資訊,如下所示:

Typicode Sourcecode

您可以按如下方式讀取 cookie:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.cookies["__cfduid"])

輸出

E:\prequests>python makeRequest.py
d1733467caa1e3431fb7f768fa79ed3741575094848

您也可以在發出請求時傳送 cookie。

示例

import requests
cookies = dict(test='test123')
getdata = requests.get('https://httpbin.org/cookies',cookies=cookies)
print(getdata.text)

輸出

E:\prequests>python makeRequest.py
{
   "cookies": {
   "test": "test123"
}
}

Requests - 處理錯誤

本章將討論如何處理使用 Http 請求庫時出現的錯誤。始終建議對所有可能的情況進行錯誤管理。

錯誤異常

requests 模組給出以下型別的錯誤異常:

ConnectionError - 如果出現任何連線錯誤,將引發此錯誤。例如,網路故障、DNS 錯誤,因此 Request 庫將引發 ConnectionError 異常。

Response.raise_for_status() - 基於狀態程式碼(例如 401、404),它將為請求的 URL 引發 HTTPError。

HTTPError - 此錯誤將針對發出的請求返回的無效響應引發。

Timeout - 為請求的 URL 超時引發的錯誤。

TooManyRedirects - 如果超過最大重定向限制,則將引發 TooManyRedirects 錯誤。

示例

以下是一個顯示超時錯誤的示例:

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
print(getdata.text)  

輸出

raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='jsonplaceholder.ty
picode.com', port=443): Max retries exceeded with url: /users (Caused by Connect
TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at
0x000000B02AD
E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect timeout= 0.001)'))   

Requests - 處理超時

超時可以輕鬆地新增到您正在請求的 URL 中。有時您使用的是第三方 URL 並等待響應。始終建議在 URL 上設定超時,因為我們可能希望 URL 在一定時間內以響應或錯誤進行響應。如果不這樣做,可能會導致無限期地等待該請求。

我們可以使用 timeout 引數為 URL 設定超時,並將值以秒為單位傳遞,如下面的示例所示:

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
print(getdata.text)    

輸出

raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='jsonplaceholder.ty
picode.com', port=443): Max retries exceeded with url: /users (Caused by Connect
TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x000000B02AD
E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect timeout=
0.001)'))

給定的超時如下:

getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)

執行將丟擲連線超時錯誤,如輸出所示。給定的超時為 0.001,這對於請求獲取響應並丟擲錯誤是不可能的。現在,我們將增加超時時間並檢查。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users',timeout=1.000)
print(getdata.text)

輸出

E:\prequests>python makeRequest.py
[
 {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
   "bs": "harness real-time e-markets"
 }

使用 1 秒的超時,我們可以獲取請求的 URL 的響應。

Requests - 處理重定向

本章將探討 Request 庫如何處理 URL 重定向情況。

示例

import requests
getdata = requests.get('http://google.com/')
print(getdata.status_code)
print(getdata.history)    

URL - http://google.com 將使用狀態程式碼 301(永久移動)重定向到 https://www.google.com/。重定向將儲存在歷史記錄中。

輸出

執行上述程式碼時,我們將獲得以下結果:

E:\prequests>python makeRequest.py
200
[<Response [301]>]

您可以使用allow_redirects=False停止 URL 的重定向。這可以在使用的 GET、POST、OPTIONS、PUT、DELETE、PATCH 方法上完成。

示例

以下是一個關於此的示例。

import requests
getdata = requests.get('http://google.com/', allow_redirects=False)
print(getdata.status_code)
print(getdata.history)
print(getdata.text)    

現在,如果您檢查輸出,則不會允許重定向,並且將獲得 301 的狀態程式碼。

輸出

E:\prequests>python makeRequest.py
301
[]
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>

Requests - 處理歷史記錄

您可以使用response.history獲取給定 URL 的歷史記錄。如果給定 URL 存在任何重定向,則它將儲存在歷史記錄中。

對於歷史記錄

import requests
getdata = requests.get('http://google.com/')
print(getdata.status_code)
print(getdata.history)  

輸出

E:\prequests>python makeRequest.py
200
[<Response [301]>]

response.history屬性將包含基於請求完成的響應物件的詳細資訊。存在的值將按從舊到新的順序排序。response.history屬性跟蹤在請求的 URL 上完成的所有重定向。

Requests - 處理會話

要維護請求之間的資料,您需要會話。因此,如果反覆呼叫同一個主機,您可以重用 TCP 連線,這將提高效能。現在讓我們看看如何使用會話維護跨請求的 cookie。

使用會話新增 cookie

import requests
req = requests.Session()
cookies = dict(test='test123')
getdata = req.get('https://httpbin.org/cookies',cookies=cookies)
print(getdata.text)    

輸出

E:\prequests>python makeRequest.py
{
   "cookies": {
   "test": "test123"
}
}

使用會話,您可以跨請求保留 cookie 資料。還可以使用會話傳遞標頭資料,如下所示:

示例

import requests
req = requests.Session()
req.headers.update({'x-user1': 'ABC'})
headers = {'x-user2': 'XYZ'}
getdata = req.get('https://httpbin.org/headers', headers=headers)    
print(getdata.headers)

Requests - SSL 證書

SSL 證書是安全 URL 附帶的安全功能。當您使用 Requests 庫時,它還會驗證給定的 https URL 的 SSL 證書。SSL 驗證在 requests 模組中預設啟用,如果證書不存在,它將引發錯誤。

使用安全 URL

以下是使用安全 URL 的示例:

import requests
getdata = requests.get(https://jsonplaceholder.typicode.com/users)
print(getdata.text) 

輸出

E:\prequests>python makeRequest.py
[
   {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
   "bs": "harness real-time e-markets"
   }
  }
]

我們很容易從上面的 https URL 獲取響應,這是因為 request 模組可以驗證 SSL 證書。

您可以透過簡單地新增 verify=False 來停用 SSL 驗證,如下面的示例所示。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify=False)
print(getdata.text)

您將獲得輸出,但它也會顯示一條警告訊息,指出未驗證 SSL 證書,建議新增證書驗證。

輸出

E:\prequests>python makeRequest.py
connectionpool.py:851: InsecureRequestWarning: Unverified HTTPS request is being
made. Adding certificate verification is strongly advised. See: https://urllib3
   .readthedocs.io/en/latest/advanced-usage.htm  l#ssl-warnings
 InsecureRequestWarning)
[
 {
  "id": 1,
   "name": "Leanne Graham",
   "username": "Bret", 
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered   client-server neural-net",
   "bs": "harness real-time e-markets"
  }
 }
]

您還可以透過在您的端託管 SSL 證書,並使用verify引數提供路徑來驗證 SSL 證書,如下所示。

示例

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users', verify='C:\Users\AppData\Local\certificate.txt')
print(getdata.text)  

輸出

E:\prequests>python makeRequest.py
[
  {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered   client-server neural-net",
   "bs": "harness real-time e-markets"
   }
  }
] 

Requests - 身份驗證

本章將討論 Requests 模組中可用的身份驗證型別。

我們將討論以下內容:

  • HTTP 請求中的身份驗證工作原理

  • 基本身份驗證

  • 摘要身份驗證

  • OAuth2 身份驗證

HTTP 請求中的身份驗證工作原理

HTTP 身份驗證位於伺服器端,當客戶端請求 URL 時,它會要求提供一些身份驗證資訊,例如使用者名稱和密碼。這是對交換的請求和響應的額外安全保障。

從客戶端方面,這些額外的身份驗證資訊(即使用者名稱和密碼)可以傳送到標頭中,稍後伺服器端將對其進行驗證。只有在身份驗證有效時,伺服器端才會傳遞響應。

Requests 庫在 requests.auth 中提供了最常用的身份驗證,即基本身份驗證(HTTPBasicAuth)和摘要身份驗證(HTTPDigestAuth)。

基本身份驗證

這是向伺服器提供身份驗證的最簡單形式。要使用基本身份驗證,我們將使用 requests 庫提供的 HTTPBasicAuth 類。

示例

以下是如何使用它的工作示例。

import requests
from requests.auth import HTTPBasicAuth
response_data = requests.get('httpbin.org/basic-auth/admin/admin123', auth=HTTPDigestAuth('admin', 'admin123'))
print(response_data.text)  

我們正在呼叫 URL https://httpbin.org/basic-auth/admin/admin123,其中使用者為admin,密碼為admin123

因此,此 URL 在沒有身份驗證(即使用者名稱和密碼)的情況下將無法工作。只有在使用 auth 引數提供身份驗證後,伺服器才會返回響應。

輸出

E:\prequests>python makeRequest.py
{
   "authenticated": true,
   "user": "admin"
}

摘要身份驗證

這是 requests 提供的另一種身份驗證形式。我們將使用 requests 的 HTTPDigestAuth 類。

示例

import requests
from requests.auth import HTTPDigestAuth
response_data = requests.get('https://httpbin.org/digest-auth/auth/admin/admin123>, auth=HTTPDigestAuth('admin', 'admin123'))
print(response_data.text)

輸出

E:\prequests>python makeRequest.py
{
   "authenticated": true,
   "user": "admin"
}

OAuth2 身份驗證

要使用 OAuth2 身份驗證,我們需要“requests_oauth2”庫。要安裝“requests_oauth2”,請執行以下操作:

pip install requests_oauth2

安裝過程中,你的終端顯示內容將如下所示:

E:\prequests>pip install requests_oauth2
Collecting requests_oauth2
Downloading https://files.pythonhosted.org/packages/52/dc/01c3c75e6e7341a2c7a9
71d111d7105df230ddb74b5d4e10a3dabb61750c/requests-oauth2-0.3.0.tar.gz
Requirement already satisfied: requests in c:\users\xyz\appdata\local\programs
\python\python37\lib\site-packages (from requests_oauth2) (2.22.0)
Requirement already satisfied: six in c:\users\xyz\appdata\local\programs\pyth
on\python37\lib\site-packages (from requests_oauth2) (1.12.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in c:\use
rs\xyz\appdata\local\programs\python\python37\lib\site-packages (from requests
->requests_oauth2) (1.25.3)
Requirement already satisfied: certifi>=2017.4.17 in c:\users\xyz\appdata\loca
l\programs\python\python37\lib\site-packages (from requests->requests_oauth2) (2
019.3.9)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in c:\users\xyz\appdata\l
ocal\programs\python\python37\lib\site-packages (from requests->requests_oauth2)
(3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in c:\users\xyz\appdata\local\pr
ograms\python\python37\lib\site-packages (from requests->requests_oauth2) (2.8)
Building wheels for collected packages: requests-oauth2
Building wheel for requests-oauth2 (setup.py) ... done
Stored in directory: C:\Users\xyz\AppData\Local\pip\Cache\wheels\90\ef\b4\43
3743cbbc488463491da7df510d41c4e5aa28213caeedd586
Successfully built requests-oauth2

我們已完成“requests-oauth2”的安裝。為了使用Google、Twitter的API,我們需要它們的授權,而這可以透過OAuth2認證來實現。

對於OAuth2認證,我們需要客戶端ID和金鑰。獲取它們的方法詳情,請參考https://developers.google.com/identity/protocols/OAuth2

之後,登入Google API控制檯(網址: https://console.developers.google.com/)並獲取客戶端ID和金鑰。

示例

以下是如何使用“requests-oauth2”的示例。

import requests
from requests_oauth2.services import GoogleClient
google_auth = GoogleClient(
   client_id="xxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com",
redirect_uri="https:///auth/success.html",
)
a = google_auth.authorize_url(
   scope=["profile", "email"],
   response_type="code",
)
res = requests.get(a)
print(res.url)

我們無法重定向到給定的URL,因為它需要登入Gmail賬戶,但是從這個示例中,你可以看到google_auth工作正常,並且給出了授權的URL。

輸出

E:\prequests>python oauthRequest.py
https://#/o/oauth2/auth?redirect_uri=
http%3A%2F%2Flocalhost%2Fauth%2Fsuccess.html&
client_id=xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com&
scope=profile+email&response_type=code

Requests - 事件鉤子

我們可以使用事件鉤子向請求的URL新增事件。在下面的示例中,我們將新增一個回撥函式,當響應可用時會呼叫該函式。

示例

要添加回調,我們需要使用hooks引數,如下例所示:

mport requests
def printData(r, *args, **kwargs):
   print(r.url)
   print(r.text)
getdata = requests.get('https://jsonplaceholder.typicode.com/users', 
hooks={'response': printData})  

輸出

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users
[
{
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
    "lat": "-37.3159",
    "lng": "81.1496"
   }
  }, 
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
   "bs": "harness real-time e-markets"
   }
  }
]

你還可以呼叫多個回撥函式,如下所示:

示例

import requests
def printRequestedUrl(r, *args, **kwargs):
   print(r.url)
def printData(r, *args, **kwargs):
   print(r.text)
getdata = requests.get('https://jsonplaceholder.typicode.com/users', hooks={'response': [printRequestedUrl, printData]})

輸出

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users
[
  {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
 }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
   }
  }
]

你也可以將鉤子新增到建立的Session中,如下所示:

示例

import requests
def printData(r, *args, **kwargs):
print(r.text)
s = requests.Session()
s.hooks['response'].append(printData)
s.get('https://jsonplaceholder.typicode.com/users')

輸出

E:\prequests>python makeRequest.py
[
 {
   "id": 1,
   "name": "Leanne Graham",
   "username": "Bret",
   "email": "Sincere@april.biz",
   "address": {
   "street": "Kulas Light",
   "suite": "Apt. 556",
   "city": "Gwenborough",
   "zipcode": "92998-3874",
   "geo": {
   "lat": "-37.3159",
   "lng": "81.1496"
   }
  },
   "phone": "1-770-736-8031 x56442",
   "website": "hildegard.org",
   "company": {
   "name": "Romaguera-Crona",
   "catchPhrase": "Multi-layered client-server neural-net",
   "bs": "harness real-time e-markets"
   }
  }
]

Requests - 代理

到目前為止,我們已經看到了客戶端直接連線並與伺服器通訊的情況。使用代理,互動過程如下:

  • 客戶端向代理傳送請求。

  • 代理將請求傳送到伺服器。

  • 伺服器將響應傳送回代理。

  • 代理將響應傳送回客戶端。

使用Http代理可以提供額外的安全措施來管理客戶端和伺服器之間的資料交換。requests庫也提供了處理代理的功能,使用proxies引數,如下所示:

示例

import requests
proxies = {
'http': 'https://:8080'
}
res = requests.get('http://httpbin.org/', proxies=proxies)
print(res.status_code) 

請求將路由到('https://:8080 URL。

輸出

200

Requests - 使用 Requests 進行網頁抓取

我們已經瞭解瞭如何使用Python requests庫從給定的URL獲取資料。我們將嘗試使用以下方法從Tutorialspoint網站(網址:https://tutorialspoint.tw/tutorialslibrary.htm)抓取資料:

  • Requests庫

  • Python的Beautiful Soup庫

我們已經安裝了Requests庫,現在讓我們安裝Beautiful Soup包。如果你想探索Beautiful Soup的更多功能,可以訪問其官方網站:https://www.crummy.com/software/BeautifulSoup/bs4/doc/

安裝Beautifulsoup

我們將看到如何安裝Beautiful Soup:

E:\prequests>pip install beautifulsoup4
Collecting beautifulsoup4
Downloading https://files.pythonhosted.org/packages/3b/c8/a55eb6ea11cd7e5ac4ba
cdf92bac4693b90d3ba79268be16527555e186f0/beautifulsoup4-4.8.1-py3-none-any.whl (
101kB)
|████████████████████████████████| 102kB 22kB/s
Collecting soupsieve>=1.2 (from beautifulsoup4)
Downloading https://files.pythonhosted.org/packages/81/94/03c0f04471fc245d08d0
a99f7946ac228ca98da4fa75796c507f61e688c2/soupsieve-1.9.5-py2.py3-none-any.whl
Installing collected packages: soupsieve, beautifulsoup4
Successfully installed beautifulsoup4-4.8.1 soupsieve-1.9.5

現在我們已經安裝了Python requests庫和Beautiful Soup。

現在讓我們編寫程式碼,從給定的URL抓取資料。

網頁抓取

import requests
from bs4 import BeautifulSoup
res = requests.get('https://tutorialspoint.tw/tutorialslibrary.htm')
print("The status code is ", res.status_code)
print("\n")
soup_data = BeautifulSoup(res.text, 'html.parser')
print(soup_data.title)
print("\n")
print(soup_data.find_all('h4'))

使用requests庫,我們可以獲取給定URL的內容,而Beautiful Soup庫則可以解析它並按照我們想要的方式獲取詳細資訊。

你可以使用Beautiful Soup庫透過Html標籤、類、ID、CSS選擇器等多種方式獲取資料。以下是我們獲得的輸出,其中我們列印了頁面的標題以及頁面上的所有h4標籤。

輸出

E:\prequests>python makeRequest.py
The status code is 200
<title>Free Online Tutorials and Courses</title>
[<h4>Academic</h4>, <h4>Computer Science</h4>, <h4>Digital Marketing</h4>, <h4>M
onuments</h4>,<h4>Machine Learning</h4>, <h4>Mathematics</h4>, <h4>Mobile Devel
opment</h4>,<h4>SAP</h4>, <h4>Software Quality</h4>, <h4>Big Data & Analyti
cs</h4>, <h4>Databases</h4>, <h4>Engineering Tutorials</h4>, <h4>Mainframe Devel
opment</h4>, <h4>Microsoft Technologies</h4>, <h4>Java Technologies</h4>,<h4>XM
L Technologies</h4>, <h4>Python Technologies</h4>, <h4>Sports</h4>, <h4>Computer
Programming</h4>,<h4>DevOps</h4>, <h4>Latest Technologies</h4>, <h4>Telecom</h4>, <h4>Exams Syllabus</h4>, <h4>UPSC IAS Exams</h4>, <h4>Web Development</h4>,
<h4>Scripts</h4>, <h4>Management</h4>,<h4>Soft Skills</h4>, <h4>Selected Readin
g</h4>, <h4>Misc</h4>]
廣告

© . All rights reserved.