Requests - 使用 Requests

在本章中,我们将了解如何使用 Requests 请求模块。我们将研究以下内容 −

  • 发出 HTTP 请求。
  • 将参数传递给 HTTP 请求。

发出 HTTP 请求

要发出 Http 请求,我们需要首先导入请求模块,如下所示 −

import request

现在让我们看看如何使用请求模块调用 URL。

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

示例

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

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

输出

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

要从响应中获取内容,我们可以使用 getdata.content 进行操作,如下所示 −

示例

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

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

输出

E:\prequests>python makeRequest.py
b'[
 {
  "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.149
6"
 }
 },
  "phone": "1-770-736-8031 x56442",
  "website": "hild
egard.org",
  "company": {
 "name": "Romaguera-Crona",
  "catchPhr
ase": "Multi-layered client-server neural-net",
  "bs": "harness real-time
e-markets"
 }
 }

向 HTTP 请求传递参数

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

参数大多以键/值对的形式传递,例如 −

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

因此,我们有 id = 9 和 username = Delphine。现在,我们将看到如何将这些数据传递给请求 Http 模块。

示例

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

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

输出

E:\prequests>python makeRequest.py
b'[
 {
 "id": 9,
 "name": "Glenna Reichert",
 "username": "Delphin
e",
 "email": "Chaim_McDermott@dana.io",
 "address": {
 "street":
"Dayna Park",
 "suite": "Suite 449",
 "city": "Bartholomebury",

"zipcode": "76495-3109",
 "geo": {
 "lat": "24.6463",

"lng": "-168.8889"
 }
 },
 "phone": "(775)976-6794 x41206",
 "
website": "conrad.com",
 "company": {
 "name": "Yost and Sons",

"catchPhrase": "Switchable contextually-based project",
 "bs": "aggregate
real-time technologies"
 }
 }
]'

我们现在在响应中获取 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