Python Http 请求
外观
Python HTTP请求[编辑 | 编辑源代码]
Python HTTP请求是指使用Python编程语言向网络服务器发送HTTP(超文本传输协议)请求的过程。HTTP请求是客户端(如浏览器或Python脚本)与服务器之间通信的基础,常用于获取网页内容、提交表单数据或与API交互。Python提供了多个库(如urllib
、requests
)来简化HTTP请求的发送与响应处理。
HTTP协议基础[编辑 | 编辑源代码]
HTTP是一种无状态的请求-响应协议,客户端向服务器发送请求,服务器返回响应。常见的HTTP方法包括:
- GET:请求获取资源(如网页)。
- POST:提交数据到服务器(如表单提交)。
- PUT:更新服务器上的资源。
- DELETE:删除服务器上的资源。
HTTP请求的组成:
- 请求行:包含方法、URL和协议版本(如
GET /index.html HTTP/1.1
)。 - 请求头:附加信息(如
User-Agent
、Content-Type
)。 - 请求体(可选):发送的数据(如POST请求的表单内容)。
Python实现HTTP请求[编辑 | 编辑源代码]
使用urllib
库[编辑 | 编辑源代码]
Python标准库urllib.request
提供基本的HTTP请求功能。
from urllib.request import urlopen
# 发送GET请求
response = urlopen("https://example.com")
print(response.read().decode('utf-8')) # 输出网页内容
输出示例(截断):
<!doctype html> <html> <head> <title>Example Domain</title> ... </html>
使用requests
库[编辑 | 编辑源代码]
第三方库requests
更简洁且功能强大,需通过pip install requests
安装。
import requests
# 发送GET请求
response = requests.get("https://api.github.com")
print(response.status_code) # 输出状态码(如200)
print(response.json()) # 解析JSON响应
输出示例:
200 {'current_user_url': 'https://api.github.com/user', ...}
POST请求示例[编辑 | 编辑源代码]
import requests
# 发送POST请求(提交JSON数据)
data = {"name": "Alice", "age": 25}
response = requests.post("https://httpbin.org/post", json=data)
print(response.json())
输出示例:
{ "args": {}, "data": "{\"name\": \"Alice\", \"age\": 25}", "headers": {"Content-Type": "application/json"}, "json": {"name": "Alice", "age": 25}, ... }
高级功能[编辑 | 编辑源代码]
请求头定制[编辑 | 编辑源代码]
通过headers
参数添加自定义头:
headers = {"User-Agent": "MyApp/1.0"}
response = requests.get("https://example.com", headers=headers)
超时设置[编辑 | 编辑源代码]
避免请求无限等待:
try:
response = requests.get("https://example.com", timeout=5) # 5秒超时
except requests.Timeout:
print("请求超时")
会话管理[编辑 | 编辑源代码]
使用Session
对象保持会话(如处理Cookies):
session = requests.Session()
session.get("https://example.com/login", params={"user": "admin"})
response = session.get("https://example.com/dashboard") # 保持登录状态
实际应用案例[编辑 | 编辑源代码]
案例1:获取天气API数据[编辑 | 编辑源代码]
import requests
# 请求开放天气API(需替换API_KEY)
api_key = "YOUR_API_KEY"
city = "London"
url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid={api_key}"
response = requests.get(url)
weather_data = response.json()
print(f"当前温度:{weather_data['main']['temp'] - 273.15:.1f}°C")
案例2:网页内容抓取[编辑 | 编辑源代码]
from bs4 import BeautifulSoup
import requests
response = requests.get("https://example.com")
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string) # 输出网页标题
错误处理[编辑 | 编辑源代码]
常见HTTP错误码:
- 4xx:客户端错误(如404资源不存在)。
- 5xx:服务器错误(如500内部错误)。
try:
response = requests.get("https://example.com/404")
response.raise_for_status() # 检查HTTP错误
except requests.HTTPError as e:
print(f"HTTP错误:{e}")
性能优化[编辑 | 编辑源代码]
- 使用连接池(
requests.Session
复用TCP连接)。 - 启用
gzip
压缩(默认支持)。 - 异步请求(如
aiohttp
库)。
数学基础[编辑 | 编辑源代码]
HTTP请求延迟由以下因素决定: 其中:
- :DNS解析时间
- :TCP握手时间
- :请求发送时间
- :服务器处理时间
- :响应返回时间
总结[编辑 | 编辑源代码]
Python的HTTP请求工具链丰富,从标准库urllib
到第三方库requests
,适合不同场景需求。掌握HTTP协议细节、错误处理和性能优化技巧,能有效提升网络编程效率。