答案:Python中发送HTTP请求常用urllib和requests库。首先,urllib是标准库,无需安装,适合基础GET和POST请求,但代码较繁琐;例如用urllib.request.urlopen发送GET请求,或构建Request对象发送POST数据。其次,推荐使用requests库,需pip install requests,其语法简洁、功能强大,支持自动处理编码、JSON解析等。可使用requests.get()发送GET请求,带params参数传递查询字符串;用requests.post()提交表单或JSON数据,通过json参数直接发送JSON。还可设置headers添加User-Agent或Authorization认证信息,支持auth参数进行HTTP基本认证。实际应用中应捕获requests.exceptions.RequestException异常,并用response.raise_for_status()检查响应状态码,确保请求成功。综上,requests适用于大多数项目,urllib可用于无外部依赖场景,掌握二者可高效实现API调用与网页抓取。

发送HTTP请求是Python中常见的网络操作,常用于与Web API交互、获取网页内容等。Python标准库和第三方库都提供了简单高效的方法来实现。下面介绍几种常用的发送HTTP请求的方式,并附上实用示例。
Python自带的urllib模块无需安装,适合基础请求场景。
GET请求示例:
import urllib.request
import urllib.parse
<p>url = '<a href="https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2">https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2</a>'
response = urllib.request.urlopen(url)
data = response.read().decode('utf-8')
print(data)</p>POST请求示例:
立即学习“Python免费学习笔记(深入)”;
data = urllib.parse.urlencode({'name': 'Tom', 'age': 25}).encode()
req = urllib.request.Request('https://httpbin.org/post', data=data)
response = urllib.request.urlopen(req)
print(response.read().decode('utf-8'))
urllib功能完整但代码略显繁琐,适合轻量需求或不想引入外部依赖的项目。
requests是Python中最流行的HTTP库,语法简洁,功能强大,需先安装:
pip install requests
GET请求:
import requests
<p>response = requests.get('<a href="https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2">https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2</a>')
print(response.status_code)
print(response.json())</p>带参数的GET请求:
params = {'q': 'python', 'page': 1}
response = requests.get('https://www.php.cn/link/4d2fe2e8601f7a8018594d98f28706f2', params=params)
POST提交表单数据:
data = {'username': 'test', 'password': '123456'}
response = requests.post('https://httpbin.org/post', data=data)
发送JSON数据:
json_data = {'name': 'Alice', 'score': 95}
response = requests.post('https://httpbin.org/post', json=json_data)
requests自动处理编码、JSON解析、会话保持等,开发效率高,是大多数项目的首选。
很多API需要设置User-Agent或Authorization头。
headers = {
'User-Agent': 'Mozilla/5.0',
'Authorization': 'Bearer your-token-here'
}
response = requests.get('https://api.example.com/data', headers=headers)
对于需要登录的接口,可使用:
response = requests.get('https://httpbin.org/basic-auth/user/pass', auth=('user', 'pass'))
实际使用中要检查状态码并捕获网络异常。
try:
response = requests.get('https://httpbin.org/status/200', timeout=5)
response.raise_for_status() # 抛出4xx/5xx错误
print(response.text)
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
可用response.status_code判断结果,用response.text或response.json()获取内容。
基本上就这些。日常开发建议用requests,简单清晰。urllib作为内置方案可在受限环境中使用。掌握这些方法后,调用REST API、抓取网页数据都不成问题。
以上就是PythonHTTP请求怎么发_Python发送HTTP请求的方法与实例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号