如何使用Python进行HTTP请求操作?
时间: 2024-12-30 10:38:35 浏览: 14
在Python中,可以使用多种库来发送HTTP请求,其中最常用的是requests
库。以下是使用requests
库发送GET、POST等基本类型的HTTP请求的基本步骤:
安装requests库 (如果还没有安装):
pip install requests
导入requests模块:
import requests
发送GET请求:
response = requests.get('https://api.example.com/data')
response
是一个Response
对象,包含了服务器返回的数据。获取响应内容:
- 状态码(例如200表示成功):
status_code = response.status_code
- 内容通常作为文本(默认编码是UTF-8):
data = response.text
- 状态码(例如200表示成功):
发送POST请求(包含数据):
payload = {'key': 'value'} response = requests.post('https://api.example.com/submit', json=payload)
使用
json=
关键字将字典转换为JSON格式发送。处理响应头和cookies:
headers = {'User-Agent': 'Mozilla/5.0'} cookies = {'session_token': 'your_cookie_value'} response = requests.get('http://example.com', headers=headers, cookies=cookies)
异常处理(可能出现网络错误):
try: response = requests.get('...') except requests.exceptions.RequestException as e: print(e)
相关推荐
















