Python网络数据采集利器 - Requests库的使用指南
简介
在Python网络爬虫领域,优秀的第三方库Requests可谓是必学的重要工具。它提供了相当人性化的API,让我们能够用极其简洁的代码发送HTTP/HTTPS请求,并且自动处理cookies、headers、编码等诸多繁琐细节,大大减轻了网页抓取的编程负担。本文将全面介绍Requests库的主要功能和使用方式。
1. 基本使用
发送一个最基本的GET请求只需一行代码:
import requests
resp = requests.get('https://www.example.com')
返回一个Response对象,包含服务器响应数据。可以调用它的text和content属性获取响应内容:
html = resp.text # 响应内容字符串形式
binary = resp.content # 响应内容字节流形式
2. 传递URL参数
使用params参数传递查询参数:
payload = {'key1': 'value1', 'key2': 'value2'}
resp = requests.get('https://httpbin.org/get', params=payload)
3. 发送其他请求
除GET外还可发送POST、PUT、DELETE、HEAD、OPTIONS请求:
requests.post('https://httpbin.org/post', data={'k':'v'})
requests.put('https://httpbin.org/put', json={'k':'v'})
requests.delete('https://httpbin.org/delete')
4. 设置请求头
通过headers参数传入字典对象:
headers = {'User-Agent': 'Myspider/1.0'}
resp = requests.get('https://www.example.com', headers=headers)
5. HTTPS和证书验证
对于HTTPS链接,默认执行安全证书验证。通过verify参数可关闭或指定CA证书:
resp = requests.get('https://example.com', verify=False)
resp = requests.get('https://example.com', verify='/path/to/cacert.pem')
6. Cookies传递
手动传入字典或通过RequestsCookieJar对象管理:
cookies = {'k1': 'v1', 'k2': 'v2'}
resp = requests.get('https://example.com/cookies', cookies=cookies)jar = requests.cookies.RequestsCookieJar()
jar.set('k1', 'v1')
resp = requests.get('https://example.com/cookies', cookies=jar)
7. 文件上传
使用files参数传入文件对象:
files = {'file': open('data.txt', 'rb')}
resp = requests.post('https://httpbin.org/post', files=files)
8. 处理重定向和超时
通过allow_redirects和timeout参数控制重定向和超时时间。
9. 会话对象
通过Session对象跨请求保持状态,自动处理cookies等。
s = requests.Session()
s.get('https://example.com/auth') # 发送认证请求
resp = s.get('https://example.com/data') # 使用认证凭据访问数据
以上就是Requests库的主要使用方式,它提供了高层次、人性化的Python HTTP客户端操作接口,极大简化了网络请求的编程工作,无疑是爬虫开发者的必备利器。当然,功能更加强大的Scrapy爬虫框架也是基于Requests库实现的。总之,掌握了Requests,您就可以开启网络数据采集之旅了。