在 Python 爬虫中发送 HTTP 请求,可使用 requests 库:安装 requests 库导入 requests 模块发送 GET 请求处理请求响应(获取状态码、头信息和内容)发送 POST 请求

如何使用 Python 爬虫发送 HTTP 请求
在 Python 爬虫中发送 HTTP 请求是访问和抓取 Web 页面内容的关键步骤。以下是如何通过 Python 的 requests 库轻松发送 HTTP 请求。
1. 安装 requests 库
pip install requests
2. 导入 requests 模块
立即学习“Python免费学习笔记(深入)”;
import requests
3. 发送 GET 请求
url = 'https://example.com' response = requests.get(url)
4. 处理请求响应
HTTP 请求返回一个 Response 对象,包含以下信息:
-
response.status_code: HTTP 状态码 -
response.headers: HTTP 头信息 -
response.content: 请求内容
示例:
if response.status_code == 200:
print('请求成功!')
else:
print(f'请求失败,状态码:{response.status_code}')5. 发送 POST 请求
url = 'https://example.com/submit'
data = {'username': 'user', 'password': 'password'}
response = requests.post(url, data=data)示例:
if response.status_code == 200:
print('提交成功!')
else:
print(f'提交失败,状态码:{response.status_code}')高级用法:
-
设置超时:
requests.get(url, timeout=10) -
使用会话:
with requests.Session() as session: -
代理支持:
requests.get(url, proxies={'http': 'http://proxy.example.com'})










