PythonHTTP请求怎么发_Python发送HTTP请求的方法与实例

答案: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请求的方式,并附上实用示例。

使用内置urllib发送请求

Python自带的urllib模块无需安装,适合基础请求场景。

GET请求示例:

import urllib.request
import urllib.parse

url = 'https://www./link/4d2fe2e8601f7a8018594d98f28706f2' response = urllib.request.urlopen(url) data = response.read().decode('utf-8') print(data)

POST请求示例:

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库(推荐)

requests是Python中最流行的HTTP库,语法简洁,功能强大,需先安装:

pip install requests

GET请求:

import requests

response = requests.get('https://www./link/4d2fe2e8601f7a8018594d98f28706f2') print(response.status_code) print(response.json())

带参数的GET请求:

params = {'q': 'python', 'page': 1}
response = requests.get('https://www./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.textresponse.json()获取内容。

基本上就这些。日常开发建议用requests,简单清晰。urllib作为内置方案可在受限环境中使用。掌握这些方法后,调用REST API、抓取网页数据都不成问题。