使用gevent实现高效异步请求
gevent:异步理论与实战 轻盈高效的异步访问库grequests库 之前我们分享了几篇异步爬虫理论及实战的文章,最近在爬一个网站的数据,一开始使用常规方式(同步)发现特别慢,基本上一秒钟才能得到一条数据。为了加快速度,还是得使用异步方法。 常用的异步库有gevent,但在这次实战中使用gevent时出现了问题。 错误代码 省略了爬虫逻辑部分 ,因为 问题出在各种库导入的先后顺序 。 import gevent from gevent import monkey import requests
monkey.patch_all()
#后面的代码省略
出现的Bug如下。 Traceback (most recent call last): File "gevent_requests.py", line 7, in <module> create_urllib3_context() File "/usr/lib/python3.6/site-packages/urllib3/util/ssl_.py", line 269, in create_urllib 3_context context.options |= options File "/usr/lib/python3.6/ssl.py", line 459, in options super(SSLContext, SSLContext).options.__set__(self, value) File "/usr/lib/python3.6/ssl.py", line 459, in options super(SSLContext, SSLContext).options.__set__(self, value) File "/usr/lib/python3.6/ssl.py", line 459, in options super(SSLContext, SSLContext).options.__set__(self, value) [Previous line repeated 329 more times] RecursionError: maximum recursion depth exceeded while calling a Python object
经过查阅,发现已经有高人解决了这个问题。 https://github.com/gevent/gevent/issues/1016
意思是说导入其他库之前,应该先使用猴子补丁。
原先的代码为 import gevent from gevent import monkey import requests
monkey.patch_all()
#后面的代码省略
更改后能正常运行的代码为 from gevent import monkey monkey.patch_all()
import gevent import requests
#后面的代码省略
现在大家再使用gevent库或者grequests就不会再遇到这个Bug了。
|