答案:使用requests库可简洁发送HTTP请求。通过get()、post()等方法发送请求,配合params、headers、json等参数传递数据,利用raise_for_status()处理错误,使用Session保持会话、复用连接,提升效率与代码可读性。

Python中发送HTTP请求,最简洁、最符合直觉的方式莫过于使用
requests
使用
requests
get()
post()
put()
delete()
pip install requests
安装完毕,我们就可以开始使用了。最常见的操作是发送GET请求来获取资源,比如从一个API端点拉取数据:
import requests
# 1. 发送一个简单的GET请求
try:
response = requests.get('https://api.github.com/users/octocat')
# 检查响应状态码,如果不是200,会抛出HTTPError
response.raise_for_status()
# 打印响应内容
print("GET请求成功!")
print(f"状态码: {response.status_code}")
print(f"响应头: {response.headers['Content-Type']}")
print(f"响应JSON数据: {response.json()}")
except requests.exceptions.HTTPError as errh:
print(f"HTTP错误: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"连接错误: {errc}")
except requests.exceptions.Timeout as errt:
print(f"超时错误: {errt}")
except requests.exceptions.RequestException as err:
print(f"其他请求错误: {err}")
print("-" * 30)
# 2. 发送一个POST请求,通常用于提交数据
# 假设我们想向一个虚拟的API提交一些数据
post_data = {
'name': 'John Doe',
'email': 'john.doe@example.com',
'message': 'Hello from Python requests!'
}
# 对于JSON数据,使用json参数更方便,requests会自动设置Content-Type为application/json
try:
post_response = requests.post('https://httpbin.org/post', json=post_data)
post_response.raise_for_status()
print("POST请求成功!")
print(f"状态码: {post_response.status_code}")
print(f"服务器收到的JSON数据: {post_response.json()['json']}")
except requests.exceptions.RequestException as err:
print(f"POST请求错误: {err}")
print("-" * 30)
# 3. 发送带查询参数的GET请求
# 比如搜索GitHub仓库
params = {'q': 'requests+language:python', 'sort': 'stars', 'order': 'desc'}
try:
search_response = requests.get('https://api.github.com/search/repositories', params=params)
search_response.raise_for_status()
print("带参数的GET请求成功!")
print(f"第一个搜索结果的名称: {search_response.json()['items'][0]['full_name']}")
except requests.exceptions.RequestException as err:
print(f"带参数的GET请求错误: {err}")这段代码展示了
requests
立即学习“Python免费学习笔记(深入)”;
在实际的Web交互中,网络请求往往是脆弱的,各种意外情况层出不穷:网络中断、服务器无响应、请求超时、认证失败、API返回错误状态码等等。因此,仅仅发送请求是不够的,我们必须妥善处理这些潜在的错误,才能让我们的程序足够健壮。
requests
requests.exceptions
try...except
requests.exceptions.ConnectionError
requests.exceptions.Timeout
但我个人觉得,最常用也最关键的一个是
response.raise_for_status()
requests.exceptions.HTTPError
response.status_code >= 400
举个例子,假设你正在调用一个需要认证的API,但你忘记传递Token,服务器很可能会返回一个401 Unauthorized。如果你没有使用
raise_for_status()
HTTPError
except
import requests
# 尝试访问一个不存在的页面,预期会得到404
try:
bad_response = requests.get('https://httpbin.org/status/404')
bad_response.raise_for_status() # 这里会抛出HTTPError
print("这个不应该被打印出来")
except requests.exceptions.HTTPError as e:
print(f"捕获到HTTP错误: {e}")
print(f"错误状态码: {e.response.status_code}")
except requests.exceptions.RequestException as e:
print(f"捕获到其他请求错误: {e}")
# 模拟一个连接超时
try:
# 设置一个非常短的超时时间,例如0.001秒
requests.get('https://www.google.com', timeout=0.001)
except requests.exceptions.Timeout as e:
print(f"捕获到超时错误: {e}")
except requests.exceptions.RequestException as e:
print(f"捕获到其他请求错误: {e}")通过这样的组合,我们不仅能应对网络连接层面的问题,也能有效处理HTTP协议层面的错误,让程序在面对各种“不确定性”时,依然能保持优雅和稳定。
很多时候,简单的GET或POST请求是远远不够的。真实的Web服务往往要求我们发送更复杂的请求,比如带查询参数、自定义HTTP头部、表单数据、JSON负载,甚至是各种形式的认证信息。
requests
1. 查询参数 (Query Parameters): 前面已经提过,对于GET请求,我们可以通过
params
requests
# 搜索GitHub仓库,指定语言和排序方式
params = {'q': 'python web framework', 'language': 'python', 'sort': 'stars', 'order': 'desc'}
response = requests.get('https://api.github.com/search/repositories', params=params)
print(f"查询参数请求URL: {response.url}")这样,URL就会变成类似
https://api.github.com/search/repositories?q=python+web+framework&language=python&sort=stars&order=desc
2. 自定义HTTP头部 (Custom Headers): HTTP头部非常重要,它承载着请求的元数据,比如
User-Agent
Content-Type
Authorization
headers
headers = {
'User-Agent': 'MyCustomPythonApp/1.0',
'Accept': 'application/json',
'X-Custom-Header': 'Hello from Python'
}
response = requests.get('https://httpbin.org/headers', headers=headers)
print("自定义头部请求响应:")
print(response.json()['headers']) # httpbin会回显所有收到的头部这在与某些需要特定User-Agent或API Key的API交互时尤其有用。
3. 表单数据 (Form Data): 当我们需要模拟HTML表单提交时,通常是POST请求,并且数据以
application/x-www-form-urlencoded
requests
data
form_data = {
'username': 'testuser',
'password': 'testpassword'
}
response = requests.post('https://httpbin.org/post', data=form_data)
print("表单数据提交响应:")
print(response.json()['form']) # httpbin会回显收到的表单数据4. JSON数据 (JSON Payload): 现代API通常期望请求体是JSON格式。
requests
json
Content-Type
application/json
json.dumps()
headers
json_payload = {
'title': 'My New Post',
'body': 'This is the content of my new post.',
'userId': 1
}
response = requests.post('https://jsonplaceholder.typicode.com/posts', json=json_payload)
print("JSON数据提交响应:")
print(f"状态码: {response.status_code}")
print(response.json())5. 认证 (Authentication):
requests
基本认证:
from requests.auth import HTTPBasicAuth
response = requests.get('https://httpbin.org/basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
print(f"基本认证响应状态: {response.status_code}")
print(response.json())更简洁的方式是直接传入一个元组:
auth=('user', 'passwd')OAuth等复杂认证: 对于OAuth或其他更复杂的认证机制,通常需要手动在
headers
Authorization
requests-oauthlib
这些选项的组合使用,让
requests
在许多Web交互场景中,我们不仅仅是发送单个独立的请求。我们可能会进行一系列相关的请求,例如:先登录,然后访问用户个人资料,接着提交一个表单。在这些连续的请求中,通常需要保持一些状态,比如认证凭证(cookies)、自定义的头部信息,甚至是底层的TCP连接。这时候,
requests.Session
我发现,很多初学者在进行一系列请求时,往往会重复地在每个
requests.get()
requests.post()
headers
params
cookies
requests.Session
Session
Session
Session
Session
headers
params
auth
Session
Session
让我们通过一个例子来看看
Session
import requests
# 创建一个Session对象
s = requests.Session()
# 为Session设置默认的User-Agent头部
s.headers.update({'User-Agent': 'MyPersistentPythonClient/1.0'})
# 1. 模拟登录,获取cookies
# 假设这是一个登录接口,成功后会返回认证cookie
login_url = 'https://httpbin.org/cookies/set/sessioncookie/12345'
login_response = s.get(login_url)
print(f"登录响应状态码: {login_response.status_code}")
print(f"Session中的Cookies (登录后): {s.cookies.get('sessioncookie')}")
# 2. 访问一个需要认证的页面
# 这个请求会自动带上Session中存储的cookie
protected_url = 'https://httpbin.org/cookies'
protected_response = s.get(protected_url)
print(f"访问受保护页面响应状态码: {protected_response.status_code}")
print(f"受保护页面收到的Cookies: {protected_response.json()['cookies']}")
# 3. 发送一个POST请求,它也会使用Session的默认头部
post_data = {'item': 'new_product'}
post_response = s.post('https://httpbin.org/post', data=post_data)
print(f"POST请求响应状态码: {post_response.status_code}")
print(f"POST请求使用的User-Agent: {post_response.json()['headers']['User-Agent']}")
# 清理Session,关闭连接(可选,通常在程序结束时自动进行)
s.close()在这个例子中,
s
Session
sessioncookie
User-Agent
s
requests
httpbin.org
总而言之,当你需要进行一系列相互关联的HTTP请求,或者对性能有较高要求时,
requests.Session
以上就是如何使用Python发送HTTP请求(requests库)?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号