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

如何使用 Python 爬虫发送 HTTP 请求
在 Python 爬虫中发送 HTTP 请求是访问和抓取 Web 页面内容的关键步骤。以下是如何通过 Python 的 requests 库轻松发送 HTTP 请求。
1. 安装 requests 库
<code class="bash">pip install requests</code>
2. 导入 requests 模块
立即学习“Python免费学习笔记(深入)”;
<code class="python">import requests</code>
3. 发送 GET 请求
<code class="python">url = 'https://example.com' response = requests.get(url)</code>
4. 处理请求响应
HTTP 请求返回一个 Response 对象,包含以下信息:
response.status_code: HTTP 状态码response.headers: HTTP 头信息response.content: 请求内容示例:
<code class="python">if response.status_code == 200:
print('请求成功!')
else:
print(f'请求失败,状态码:{response.status_code}')</code>5. 发送 POST 请求
<code class="python">url = 'https://example.com/submit'
data = {'username': 'user', 'password': 'password'}
response = requests.post(url, data=data)</code>示例:
<code class="python">if response.status_code == 200:
print('提交成功!')
else:
print(f'提交失败,状态码:{response.status_code}')</code>高级用法:
requests.get(url, timeout=10)
with requests.Session() as session:
requests.get(url, proxies={'http': 'http://proxy.example.com'})
以上就是python爬虫怎么发送请求的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号