在引擎盖下,requests
uses urllib3
完成大部分 http 繁重工作。如果使用得当,它应该基本相同,除非您需要更高级的配置。
除了,在你的特定示例中,它们是not相同:
在 urllib3 示例中,您重复使用连接,而在 requests 示例中,您没有重复使用连接。您可以通过以下方法判断:
>>> import requests
>>> requests.packages.urllib3.add_stderr_logger()
2016-04-29 11:43:42,086 DEBUG Added a stderr logging handler to logger: requests.packages.urllib3
>>> requests.get('https://www.google.com/')
2016-04-29 11:45:59,043 INFO Starting new HTTPS connection (1): www.google.com
2016-04-29 11:45:59,158 DEBUG "GET / HTTP/1.1" 200 None
>>> requests.get('https://www.google.com/')
2016-04-29 11:45:59,815 INFO Starting new HTTPS connection (1): www.google.com
2016-04-29 11:45:59,925 DEBUG "GET / HTTP/1.1" 200 None
要像在 urllib3 PoolManager 中那样开始重用连接,您需要发出请求session.
>>> session = requests.session()
>>> session.get('https://www.google.com/')
2016-04-29 11:46:49,649 INFO Starting new HTTPS connection (1): www.google.com
2016-04-29 11:46:49,771 DEBUG "GET / HTTP/1.1" 200 None
>>> session.get('https://www.google.com/')
2016-04-29 11:46:50,548 DEBUG "GET / HTTP/1.1" 200 None
Now这相当于你正在做的事情http = PoolManager()
。另请注意:urllib3 是一个较低级别的更显式库,因此您显式创建一个池并且显式需要指定您的 SSL 证书位置 https://urllib3.readthedocs.io/en/latest/security.html#using-certifi-with-urllib3, 例如。这是一两行额外的工作,但如果您正在寻找的话,也需要更多的控制。
总而言之,比较就变成了:
1)使用urllib3:
import urllib3, certifi
http = urllib3.PoolManager(ca_certs=certifi.where())
html = http.request('GET', url).read()
soup = BeautifulSoup(html, "html5lib")
2)使用请求:
import requests
session = requests.session()
html = session.get(url).content
soup = BeautifulSoup(html, "html5lib")