Python Requests.get() 方法用于向指定的 URL 发送 HTTP GET 请求。此方法从指定的服务器终端节点检索数据。
此方法可以接受可选参数,例如用于查询参数的 params、用于自定义标头的 headers、用于请求超时的 timeout 和用于身份验证的 auth。
此方法返回一个 Response 对象,其中包含服务器的响应数据、状态代码、标头等。它通常用于从 API 或 Web 页面获取数据。
语法
以下是 Python 请求 get() 方法的语法和参数 -
requests.get(url, params=None, **kwargs)
参数
以下是 Python 请求 get() 方法的参数 -
- url:这是我们要获取的资源的 url。
- params(dict 或 bytes,可选):要在请求的查询字符串中发送的字典或字节。
- kwargs(可选):可以传递的可选参数,包括 headers、cookie、authentication 等。
返回值
此方法返回 Response 对象。
示例 1
以下是基本示例,涉及向指定 URL 发送请求并在 python requests.get() 方法的帮助下处理响应 -
import requests
response = requests.get('https://www.qikepu.com')
print(response.url)
输出
https://www.qikepu.com/
示例 2
get() 方法的 'params' 参数用于获取 url 的参数。此参数接受键值对的字典,该字典将在 URL 中编码为查询参数。这是示例-
import requests
params = {'q': 'python requests', 'sort': 'relevance'}
response = requests.get('https://www.qikepu.com', params=params)
print(response.url)
输出
https://www.qikepu.com/?q=python+requests&sort=relevance
示例 3
requests 模块通过在 get() 方法中指定参数 'auth' 来支持多种类型的身份验证。以下是 authenticaton 的基本示例 -
import requests
from requests.auth import HTTPBasicAuth
# Define the URL
url = 'https://httpbin.org/basic-auth/user/pass'
# Define the credentials
username = 'user'
password = 'pass'
# Send the GET request with Basic Authentication
response = requests.get(url, auth=HTTPBasicAuth(username, password))
# Print the response status code
print(response.status_code)
# Print the response content
print(response.text)
输出
200
{
"authenticated": true,
"user": "user"
}
{
"authenticated": true,
"user": "user"
}