📜  Requests-处理请求

📅  最后修改于: 2020-10-21 08:30:33             🧑  作者: Mango


 

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

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

发出HTTP请求

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

import requests 

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

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

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

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

输出

E:\prequests>python makeRequest.py

要从响应中获取内容,我们可以使用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和用户名= 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'[\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