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
廣告