安装Python的requests
模块非常简单,以下是详细步骤和注意事项:
一、安装方法
-
使用pip安装
打开命令行终端(Windows用户可使用CMD或PowerShell,macOS/Linux用户使用Terminal),输入以下命令:
pip install requests
执行后,pip会自动下载并安装最新版本的
requests
模块。 -
验证安装
安装完成后,可以通过以下方式验证:
-
在Python交互式环境中输入:
import requests print(requests.__version__)
-
运行Python脚本,尝试导入模块:
import requests
-
二、基本用法
-
发送GET请求
使用
requests.get()
方法获取网页内容:import requests response = requests.get('https://api.github.com') print(response.status_code) # 输出状态码(如200表示成功) print(response.json()) # 解析JSON响应
-
发送POST请求
传递数据到服务器:
import requests data = {'key1': 'value1', 'key2': 'value2'} response = requests.post('https://httpbin.org/post', data=data) print(response.json())
-
其他常用参数
-
带参数的请求 :使用
params
参数传递URL查询参数params = {'q': 'requests+language:python'} response = requests.get('https://api.github.com/search/repositories', params=params) print(response.json())
-
发送JSON数据 :使用
json
参数自动序列化字典data = {'name': 'example', 'description': '测试请求'} response = requests.post('https://httpbin.org/post', json=data) print(response.json())
-
三、注意事项
-
处理异常
建议使用
try-except
块捕获网络异常:import requests try: response = requests.get('https://api.example.com') response.raise_for_status() # 检查是否成功 except requests.exceptions.RequestException as e: print(f"请求失败: {e}")
-
会话与连接池
使用
requests.Session()
可复用连接,提高效率:import requests session = requests.Session() response = session.get('https://api.github.com') print(response.json())
-
自定义请求头
部分网站需伪装浏览器,可通过
headers
参数添加自定义头部:headers = {'User-Agent': 'Mozilla/5.0'} response = requests.get('https://example.com', headers=headers) print(response.text)
通过以上步骤,您可以快速掌握requests
模块的安装与基础用法,适用于API调用和网页数据抓取场景。