Python爬虫之requests库快速入门
2023-12-12 11:44:00
Python爬虫之requests库快速入门
简介
Python爬虫之requests库是一个基于 urllib,采用 Apache2 Licensed开源协议的 HTTP 库。它比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求。Requests 库是 Python 爬虫开发的必备库,它具有以下特点:
- 易于使用:Requests 库的 API 非常简单,即使是新手也可以快速上手。
- 功能强大:Requests 库提供了许多强大的功能,包括 GET、POST、PUT、DELETE、HEAD 等 HTTP 请求方法,以及 cookie、重定向、代理等支持。
- 扩展性强:Requests 库可以轻松扩展,支持各种第三方库,如 BeautifulSoup、lxml 等。
安装
Requests 库可以通过 pip 安装:
pip install requests
基本用法
Requests 库的基本用法非常简单。要发送一个 GET 请求,只需要调用 requests.get() 方法,并指定请求的 URL:
import requests
url = 'https://www.python.org'
response = requests.get(url)
Response 对象包含了服务器返回的所有信息,包括状态码、头部信息和内容。要获取响应内容,可以使用 response.text 属性:
content = response.text
要发送一个 POST 请求,只需要调用 requests.post() 方法,并指定请求的 URL 和数据:
url = 'https://www.python.org/submit'
data = {'name': 'John Doe', 'email': 'johndoe@example.com'}
response = requests.post(url, data=data)
高级用法
Requests 库提供了许多高级用法,如 cookie、重定向、代理等。
Cookie
Cookie 是服务器发送到客户端的少量数据,用于在客户端和服务器之间保持状态。要使用 cookie,可以使用 requests.cookies.RequestsCookieJar() 方法创建一个 cookie jar:
import requests
jar = requests.cookies.RequestsCookieJar()
然后,将 cookie jar 传递给 requests.get() 或 requests.post() 方法:
url = 'https://www.python.org'
response = requests.get(url, cookies=jar)
重定向
当服务器返回 301 或 302 状态码时,表示请求的资源已移动到另一个位置。Requests 库会自动处理重定向,但也可以通过 allow_redirects 参数来控制重定向行为:
import requests
url = 'https://www.python.org'
response = requests.get(url, allow_redirects=False)
代理
代理服务器可以用来隐藏客户端的真实 IP 地址。要使用代理,可以使用 requests.ProxyHandler() 方法创建一个代理处理器:
import requests
proxy = 'http://127.0.0.1:8080'
proxy_handler = requests.ProxyHandler({'http': proxy})
session = requests.Session()
session.proxies = {'http': proxy}
然后,将代理处理器添加到会话中:
session.mount('http://', proxy_handler)
常见问题解答
如何处理 HTTPS 请求?
Requests 库会自动处理 HTTPS 请求。只需要在 URL 中使用 协议即可。
如何设置超时时间?
可以使用 timeout 参数来设置超时时间:
import requests
url = 'https://www.python.org'
response = requests.get(url, timeout=10)
如何处理异常?
Requests 库会自动处理大多数异常。但也可以通过 try/except 语句来处理异常:
import requests
try:
url = 'https://www.python.org'
response = requests.get(url)
except requests.exceptions.RequestException as e:
print(e)
总结
Requests 库是 Python 爬虫开发的必备库,它具有易于使用、功能强大、扩展性强等特点。本文介绍了 Requests 库的基本用法和高级用法,以及常见问题解答。希望本文能帮助您快速入门 Requests 库,并开发出强大的爬虫程序。