Python 函数库 Requests 使用指南
Python 函数库 Requests 是一种功能强大、易于使用的 HTTP 客户端库,它允许你以更简单、更 Pythonic 的方式发送 HTTP/1.1 请求。使用 Requests 库,你可以快速、轻松地获取需要的网页内容,从而进行各种数据抓取操作。
Requests 库不仅可以进行 GET 请求,还支持 POST、PUT、DELETE 等多种 HTTP 请求方法,并且可以自定义各种请求头、Cookie 等信息。此外,Requests 还自带了强大的 Session 和认证功能,支持 HTTPS、异步请求等高级特性。
下面将介绍 Requests 库的基本用法。
安装 Requests 库
如果你使用的是 Python 2.x 版本,可以使用以下命令安装:
$ sudo pip install requests
如果你使用的是 Python 3.x 版本,可以使用以下命令安装:
$ sudo pip3 install requests
发送 HTTP 请求
使用 Requests 库发送 HTTP 请求非常简单,只需要使用相应的方法即可。以下是一些常用的 HTTP 请求方法及其用法:
1. GET 请求方法:
使用 requests.get() 方法可以发送 GET 请求:
import requests
response = requests.get('https://www.baidu.com')
print(response.text)
2. POST 请求方法:
使用 requests.post() 方法可以发送 POST 请求:
import requests
data = {'username': 'justin', 'password': '123456'}
response = requests.post('http://www.example.com/login', data=data)
print(response.text)
3. PUT 请求方法:
使用 requests.put() 方法可以发送 PUT 请求:
import requests
data = {'name': 'justin', 'age': 20}
response = requests.put('http://www.example.com/profile', data=data)
print(response.text)
4. DELETE 请求方法:
使用 requests.delete() 方法可以发送 DELETE 请求:
import requests
response = requests.delete('http://www.example.com/user/1')
print(response.text)
Requests 还支持其他 HTTP 请求方法,例如 OPTIONS、HEAD、PATCH 等,具体用法可以参见官方文档。
自定义请求头
有些网站会对访问者的 User-Agent、Referer 等信息进行检测,如果检测到不同于浏览器的请求头,就会拒绝访问。此时我们就需要自定义请求头来模拟浏览器,例如:
import requests
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
response = requests.get('https://www.baidu.com', headers=headers)
print(response.text)
自定义 Cookie
有些网站会根据 Cookie 信息来判断用户是否登录,此时我们可以使用 Cookies 字典来自定义 Cookie 信息:
import requests
cookies = {'name': 'justin', 'age': '20'}
response = requests.get('http://www.example.com', cookies=cookies)
print(response.text)
使用 Session
在使用 Requests 发送多个请求时,每次都要重新发送 Cookie、请求头等信息,会浪费很多时间和带宽。为了提高效率,Requests 提供了 Session 功能,可以在一个 Session 中执行多个请求,而且共享 Cookie、请求头等信息,避免重复发送。例如:
import requests
# 创建一个 Session 对象
s = requests.Session()
# 第一个请求
data = {'username': 'justin', 'password': '123456'}
s.post('http://www.example.com/login', data=data)
# 第二个请求
response = s.get('http://www.example.com/profile')
print(response.text)
认证
有些网站会对某些资源进行访问限制,需要进行认证才能访问。Requests 提供了基本身份验证、摘要身份验证、OAuth 认证等多种认证方式。例如:
import requests
# 基本身份验证
response = requests.get('http://www.example.com', auth=('username', 'password'))
# 摘要身份验证
response = requests.get('http://www.example.com', auth=requests.auth.HTTPDigestAuth('username', 'password'))
# OAuth 认证
headers = {'Authorization': 'Bearer access_token'}
response = requests.get('https://api.example.com/user', headers=headers)
HTTPS 请求
Requests 默认会验证 SSL 证书,如果需要跳过证书验证,可以通过 verify=False 参数来实现:
import requests
response = requests.get('https://www.example.com', verify=False)
print(response.text)
异步请求
如果需要发送大量 HTTP 请求,同步方式会阻塞程序,导致效率低下。为了提高效率,可以使用异步请求库,例如 gevent、asyncio 等。
使用 gevent 发送异步请求的代码示例:
import gevent
from gevent import monkey
monkey.patch_all()
import requests
def fetch(url):
response = requests.get(url)
print(response.text)
gevent.joinall([
gevent.spawn(fetch, 'http://www.example.com'),
gevent.spawn(fetch, 'http://www.example.com'),
gevent.spawn(fetch, 'http://www.example.com'),
])
使用 asyncio 发送异步请求的代码示例:
import asyncio
import aiohttp
async def fetch(session, url):
async with session.get(url) as response:
print(await response.text())
async def main():
async with aiohttp.ClientSession() as session:
await asyncio.gather(
fetch(session, 'http://www.example.com'),
fetch(session, 'http://www.example.com'),
fetch(session, 'http://www.example.com'),
)
asyncio.run(main())
总结
使用 Requests 库可以轻松地发送 HTTP 请求、自定义请求头和 Cookie、使用 Session 等功能。同时,它也支持 HTTPS、认证、异步请求等高级特性,能够满足各种数据抓取需求。学好 Requests 库,可以极大地提升数据爬取的效率和质量。
