Requests 简明教程

Requests - Working with Requests

在本章中,我们将了解如何使用 requests 模块。我们将探讨以下内容:

  1. Making HTTP Requests.

  2. 将参数传递给 HTTP 请求。

Making HTTP Requests

要进行 Http 请求,我们首先需要导入 request 模块,如下所示:

import requests

现在让我们了解如何使用 requests 模块发起对 URL 的调用。

让我们在代码中使用 URL − https://jsonplaceholder.typicode.com/users 来测试 Requests 模块。

Example

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

网址 − https://jsonplaceholder.typicode.com/users 使用 requests.get() 方法调用。URL 的响应对象存储在 getdata 变量中。当我们打印该变量时,它会给出 200 的响应代码,这意味着我们已成功得到响应。

Output

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

要从响应中获取内容,我们可以使用 getdata.content ,如下所示:

Example

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

getdata.content 将打印响应中所有可用数据。

Output

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 }

Passing Parameters to HTTP Requests

仅请求 URL 是不够的,我们还需要将参数传递给 URL。

params 大多以键值对传递,例如:

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

因此,我们有 id = 9 和 username = Delphine。现在将了解如何将此类数据传递给 requests Http 模块。

Example

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

这些详细信息存储在键/值对中的对象有效负载中,并传递到 get() 方法内部的 params。

Output

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。

Example

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

Output

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