python学习-python入门-03注释

本文深入探讨了Python中注释的使用方法,包括单行注释和多行注释的语法及应用场景,帮助初学者理解如何在代码中正确使用注释。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注释

  • 单行注释
    – #
# 这是第一个注释
print("hello")  # 输出hello
  • 多行注释
    – “”“ ”“”
    ···

这是第一个注释

print(“hello”)
“”"
这是多行注释
“”"
···

<think>我们使用python的requests库来发送HTTP请求。这是一个非常流行的库,用于在Python中进行HTTP通信。 我们将介绍如何使用requests库发送GET和POST请求,以及如何处理响应。 首先,确保已经安装了requests库。如果没有安装,可以通过pip安装:pip install requests 我们将通过几个简单的示例来展示: 1. 发送GET请求 2. 发送POST请求(带表单数据) 3. 发送POST请求(带JSON数据) 4. 处理响应(状态码、响应头、响应体) 5. 设置请求头 6. 处理超时 7. 错误处理 每个示例都会给出详细的注释。</think># Python requests库入门教程 requests是Python中最受欢迎的HTTP客户端库,它简化了HTTP请求的发送过程,让开发者能够轻松地与Web服务进行交互。 ## 安装requests库 ```bash pip install requests ``` ## 基本GET请求 ```python import requests # 导入requests库 # 发送一个简单的GET请求到示例API response = requests.get('https://jsonplaceholder.typicode.com/posts/1') # 检查请求是否成功(HTTP状态码200表示成功) if response.status_code == 200: # 解析响应内容为JSON格式 data = response.json() print("获取到的数据:") print(f"标题: {data['title']}") print(f"内容: {data['body']}") else: # 如果请求失败,打印错误信息 print(f"请求失败,状态码: {response.status_code}") ``` ## 带参数的GET请求 ```python import requests # 定义查询参数 params = { 'userId': 1, # 指定用户ID '_limit': 5 # 限制返回结果数量 } # 发送带查询参数的GET请求 response = requests.get( 'https://jsonplaceholder.typicode.com/posts', params=params # 传递查询参数 ) # 检查响应状态 if response.ok: # response.ok等价于200 <= status_code < 300 posts = response.json() print(f"获取到{len(posts)}篇帖子:") for i, post in enumerate(posts, 1): print(f"{i}. {post['title'][:30]}...") # 只打印标题的前30个字符 else: print(f"请求失败: {response.status_code}") ``` ## POST请求提交表单数据 ```python import requests # 目标URL(JSONPlaceholder的模拟API) url = 'https://jsonplaceholder.typicode.com/posts' # 准备要提交的表单数据 form_data = { 'title': 'requests库教程', # 帖子标题 'body': '学习使用Python requests库发送HTTP请求', # 帖子内容 'userId': 1 # 用户ID } # 发送POST请求提交表单数据 response = requests.post( url, data=form_data, # 表单数据 timeout=5 # 设置5秒超时 ) # 检查响应 if response.status_code == 201: # 201表示资源创建成功 created_post = response.json() print("帖子创建成功!") print(f"ID: {created_post['id']}") print(f"标题: {created_post['title']}") else: print(f"创建失败: {response.status_code}") print(f"响应内容: {response.text}") ``` ## POST请求提交JSON数据 ```python import requests import json # 用于JSON处理 # 目标API端点 url = 'https://jsonplaceholder.typicode.com/posts' # 准备要提交的JSON数据 json_data = { 'title': 'JSON数据示例', 'body': '使用requests发送JSON格式的数据', 'userId': 2 } # 设置请求头,指定内容类型为JSON headers = { 'Content-Type': 'application/json; charset=UTF-8' } # 发送POST请求提交JSON数据 try: response = requests.post( url, data=json.dumps(json_data), # 将字典转换为JSON字符串 headers=headers, # 设置请求头 timeout=3 # 设置3秒超时 ) # 如果响应状态码不是2xx,抛出异常 response.raise_for_status() # 自动检查HTTP错误 # 处理成功响应 result = response.json() print("JSON数据提交成功!") print(f"返回的ID: {result.get('id', '未知')}") except requests.exceptions.RequestException as e: # 捕获所有requests相关的异常 print(f"请求出错: {str(e)}") ``` ## 处理响应 ```python import requests response = requests.get('https://jsonplaceholder.typicode.com/users/1') print(f"状态码: {response.status_code}") # 打印HTTP状态码 print(f"响应头: {response.headers['Content-Type']}") # 打印内容类型 print(f"编码: {response.encoding}") # 打印响应编码 # 以文本形式获取响应内容 text_content = response.text print(f"文本内容的前100个字符: {text_content[:100]}...") # 以二进制形式获取响应内容(适用于非文本内容) binary_content = response.content # 解析JSON响应 json_data = response.json() print(f"用户名: {json_data['username']}") print(f"邮箱: {json_data['email']}") ``` ## 设置请求头 ```python import requests url = 'https://httpbin.org/headers' # 自定义请求头 headers = { 'User-Agent': 'MyPythonRequests/1.0', # 自定义用户代理 'Accept': 'application/json', # 指定接受JSON响应 'X-Custom-Header': 'HelloWorld' # 自定义头部 } response = requests.get(url, headers=headers) if response.status_code == 200: data = response.json() print("服务器接收到的请求头:") print(data['headers']) # 显示服务器接收到的请求头 ``` ## 错误处理 ```python import requests from requests.exceptions import Timeout, RequestException try: # 尝试访问一个可能不存在的URL response = requests.get( 'https://jsonplaceholder.typicode.com/invalid-endpoint', timeout=2 # 设置2秒超时 ) # 如果HTTP状态码表示错误,抛出异常 response.raise_for_status() except Timeout: print("请求超时!请检查网络连接或增加超时时间。") except requests.exceptions.HTTPError as err: print(f"HTTP错误: {err}") except RequestException as err: print(f"请求异常: {str(err)}") else: print("请求成功完成!") ``` ## 会话对象(持久连接) ```python import requests # 创建会话对象 with requests.Session() as session: # 设置公共请求头 session.headers.update({'User-Agent': 'MySessionClient/1.0'}) # 第一次请求 response1 = session.get('https://jsonplaceholder.typicode.com/users/1') print(f"第一次请求状态: {response1.status_code}") # 第二次请求(使用同一个会话) response2 = session.get('https://jsonplaceholder.typicode.com/posts?userId=1') print(f"第二次请求状态: {response2.status_code}") print(f"获取到{len(response2.json())}篇帖子") # 会话会自动管理cookies print(f"会话中的Cookies: {session.cookies.get_dict()}") ``` ## 文件上传 ```python import requests # 文件上传的URL url = 'https://httpbin.org/post' # 打开要上传的文件(注意:实际使用时替换为真实文件路径) try: # 使用二进制读取模式打开文件 with open('example.txt', 'wb') as f: f.write(b'This is a test file for requests tutorial.') # 再次以二进制模式打开文件用于上传 with open('example.txt', 'rb') as file: # 准备要上传的文件和其他表单数据 files = { 'file': ('example.txt', file, 'text/plain') # (文件名, 文件对象, MIME类型) } data = { 'description': '示例文件上传' } # 发送POST请求上传文件 response = requests.post(url, files=files, data=data) # 处理响应 if response.status_code == 200: result = response.json() print("文件上传成功!") print(f"服务器接收到的文件信息: {result['files']['file']}") else: print(f"上传失败: {response.status_code}") except FileNotFoundError: print("文件未找到!") except Exception as e: print(f"发生错误: {str(e)}") ``` ## 总结 requests库提供了简洁直观的API来处理HTTP请求: - 使用`requests.get()`发送GET请求 - 使用`requests.post()`发送POST请求 - 使用`params`参数添加查询字符串 - 使用`data`参数发送表单数据 - 使用`json`参数直接发送JSON数据 - 使用`headers`参数自定义请求头 - 使用`timeout`参数设置请求超时 - 使用`response.json()`解析JSON响应 - 使用会话(Session)对象保持持久连接 - 使用`files`参数上传文件 - 使用`raise_for_status()`检查HTTP错误 ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值