Requests - 处理 GET 请求
本章将重点介绍 GET 请求,这是最常见且最常用的请求。请求模块中 GET 的操作非常简单。这是一个使用 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'[
{
"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":
"hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase":
"Multi-layered client-server neural-net",
"bs":
"harness real-time e-markets"
}
}
您还可以使用 param 属性将参数传递给 get 方法,如下所示 −
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": "Delphine",
"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"
}
}
]'

