参考文档
HTTPRequest AsyncHTTPClient.configure HTTP 599: Timeout in request queue 异常处理
说明
tornado的AsyncHTTPClient作为爬虫客户端使用起来很方便, 但是为了应对网站的IP访问限制,这个时候就需要使用IP代理机制了, AsyncHTTPClient经过简单的配置就可以使用HTTP代理来进行http访问了, 正好结合tornado的异步机制,就可以同时开多个连接去访问不同的内容,提高爬取速度。
不过在windows上由于curl库的关系,我没有跑起来,本文的代码可以跑在linux下面。
代码
AsyncHTTPClient使用HTTP代理
import tornado.ioloop
from tornado.httpclient import HTTPRequest, AsyncHTTPClient
@tornado.gen.coroutine
def send_requ():
http_requ = HTTPRequest(
url='http://www.baidu.com',
method='GET',
proxy_host = 'a.b.c.d', # 配置HTTP代理的ip地址
proxy_port = 1234, # 设置HTTP代理的端口
)
http_resp = yield AsyncHTTPClient().fetch(http_requ)
#处理回复消息。。。
if __name__ == "__main__":
# 配置 AsyncHTTPClient
AsyncHTTPClient.configure(
"tornado.curl_httpclient.CurlAsyncHTTPClient", # 必须配置这个不然无法使用代理
max_clients=600 # 客户端池数量配置设大一点
)
tornado.ioloop.IOLoop.run_sync(send_requ)
AsyncHTTPClient禁止排队超时
上面的那段代码在程序启动时会调用AsyncHTTPClient.configure将最大的可用客户端数量设置为600了,到达600之后所有待发送的请求都会进入排队机制,但是该队列里面的请求有个排队时间,如果超时tornado将会丢弃这个请求并给调用方抛出一个异常。
tornado.httpclient.HTTPError: HTTP 599: Timeout in request queue
下面的代码可以让AsyncHTTPClient排队的请求不会超时
from tornado.httpclient import AsyncHTTPClient
from tornado.log import gen_log
from tornado.simple_httpclient import SimpleAsyncHTTPClient
class NoQueueTimeoutHTTPClient(SimpleAsyncHTTPClient):
def fetch_impl(self, request, callback):
key = object()
self.queue.append((key, request, callback))
self.waiting[key] = (request, callback, None)
self._process_queue()
if self.queue:
gen_log.debug("max_clients limit reached, request queued. %d active, %d queued requests." % (
len(self.active), len(self.queue)))
AsyncHTTPClient.configure(NoQueueTimeoutHTTPClient, max_clients=20)