跳转到内容
主菜单
主菜单
移至侧栏
隐藏
导航
首页
最近更改
随机页面
MediaWiki帮助
代码酷
搜索
搜索
中文(中国大陆)
外观
创建账号
登录
个人工具
创建账号
登录
未登录编辑者的页面
了解详情
贡献
讨论
编辑“︁
Python Http 请求
”︁
页面
讨论
大陆简体
阅读
编辑
编辑源代码
查看历史
工具
工具
移至侧栏
隐藏
操作
阅读
编辑
编辑源代码
查看历史
常规
链入页面
相关更改
特殊页面
页面信息
外观
移至侧栏
隐藏
您的更改会在有权核准的用户核准后向读者展示。
警告:
您没有登录。如果您进行任何编辑,您的IP地址会公开展示。如果您
登录
或
创建账号
,您的编辑会以您的用户名署名,此外还有其他益处。
反垃圾检查。
不要
加入这个!
= Python HTTP请求 = '''Python HTTP请求'''是指使用Python编程语言向网络服务器发送HTTP(超文本传输协议)请求的过程。HTTP请求是客户端(如浏览器或Python脚本)与服务器之间通信的基础,常用于获取网页内容、提交表单数据或与API交互。Python提供了多个库(如<code>urllib</code>、<code>requests</code>)来简化HTTP请求的发送与响应处理。 == HTTP协议基础 == HTTP是一种无状态的请求-响应协议,客户端向服务器发送请求,服务器返回响应。常见的HTTP方法包括: * '''GET''':请求获取资源(如网页)。 * '''POST''':提交数据到服务器(如表单提交)。 * '''PUT''':更新服务器上的资源。 * '''DELETE''':删除服务器上的资源。 HTTP请求的组成: * '''请求行''':包含方法、URL和协议版本(如<code>GET /index.html HTTP/1.1</code>)。 * '''请求头''':附加信息(如<code>User-Agent</code>、<code>Content-Type</code>)。 * '''请求体'''(可选):发送的数据(如POST请求的表单内容)。 == Python实现HTTP请求 == === 使用<code>urllib</code>库 === Python标准库<code>urllib.request</code>提供基本的HTTP请求功能。 <syntaxhighlight lang="python"> from urllib.request import urlopen # 发送GET请求 response = urlopen("https://example.com") print(response.read().decode('utf-8')) # 输出网页内容 </syntaxhighlight> '''输出示例'''(截断): <pre> <!doctype html> <html> <head> <title>Example Domain</title> ... </html> </pre> === 使用<code>requests</code>库 === 第三方库<code>requests</code>更简洁且功能强大,需通过<code>pip install requests</code>安装。 <syntaxhighlight lang="python"> import requests # 发送GET请求 response = requests.get("https://api.github.com") print(response.status_code) # 输出状态码(如200) print(response.json()) # 解析JSON响应 </syntaxhighlight> '''输出示例''': <pre> 200 {'current_user_url': 'https://api.github.com/user', ...} </pre> === POST请求示例 === <syntaxhighlight lang="python"> import requests # 发送POST请求(提交JSON数据) data = {"name": "Alice", "age": 25} response = requests.post("https://httpbin.org/post", json=data) print(response.json()) </syntaxhighlight> '''输出示例''': <pre> { "args": {}, "data": "{\"name\": \"Alice\", \"age\": 25}", "headers": {"Content-Type": "application/json"}, "json": {"name": "Alice", "age": 25}, ... } </pre> == 高级功能 == === 请求头定制 === 通过<code>headers</code>参数添加自定义头: <syntaxhighlight lang="python"> headers = {"User-Agent": "MyApp/1.0"} response = requests.get("https://example.com", headers=headers) </syntaxhighlight> === 超时设置 === 避免请求无限等待: <syntaxhighlight lang="python"> try: response = requests.get("https://example.com", timeout=5) # 5秒超时 except requests.Timeout: print("请求超时") </syntaxhighlight> === 会话管理 === 使用<code>Session</code>对象保持会话(如处理Cookies): <syntaxhighlight lang="python"> session = requests.Session() session.get("https://example.com/login", params={"user": "admin"}) response = session.get("https://example.com/dashboard") # 保持登录状态 </syntaxhighlight> == 实际应用案例 == === 案例1:获取天气API数据 === <syntaxhighlight lang="python"> 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") </syntaxhighlight> === 案例2:网页内容抓取 === <syntaxhighlight lang="python"> from bs4 import BeautifulSoup import requests response = requests.get("https://example.com") soup = BeautifulSoup(response.text, 'html.parser') print(soup.title.string) # 输出网页标题 </syntaxhighlight> == 错误处理 == 常见HTTP错误码: * '''4xx''':客户端错误(如404资源不存在)。 * '''5xx''':服务器错误(如500内部错误)。 <syntaxhighlight lang="python"> try: response = requests.get("https://example.com/404") response.raise_for_status() # 检查HTTP错误 except requests.HTTPError as e: print(f"HTTP错误:{e}") </syntaxhighlight> == 性能优化 == * 使用连接池(<code>requests.Session</code>复用TCP连接)。 * 启用<code>gzip</code>压缩(默认支持)。 * 异步请求(如<code>aiohttp</code>库)。 <mermaid> graph LR A[客户端] -->|GET /index.html| B[服务器] B -->|200 OK + 数据| A A -->|POST /submit JSON| B B -->|201 Created| A </mermaid> == 数学基础 == HTTP请求延迟由以下因素决定: <math> T_{total} = T_{DNS} + T_{TCP} + T_{request} + T_{process} + T_{response} </math> 其中: * <math>T_{DNS}</math>:DNS解析时间 * <math>T_{TCP}</math>:TCP握手时间 * <math>T_{request}</math>:请求发送时间 * <math>T_{process}</math>:服务器处理时间 * <math>T_{response}</math>:响应返回时间 == 总结 == Python的HTTP请求工具链丰富,从标准库<code>urllib</code>到第三方库<code>requests</code>,适合不同场景需求。掌握HTTP协议细节、错误处理和性能优化技巧,能有效提升网络编程效率。 [[Category:编程语言]] [[Category:Python]] [[Category:Python 网络编程]]
摘要:
请注意,所有对代码酷的贡献均被视为依照知识共享署名-非商业性使用-相同方式共享发表(详情请见
代码酷:著作权
)。如果您不希望您的文字作品被随意编辑和分发传播,请不要在此提交。
您同时也向我们承诺,您提交的内容为您自己所创作,或是复制自公共领域或类似自由来源。
未经许可,请勿提交受著作权保护的作品!
取消
编辑帮助
(在新窗口中打开)