Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在不请求的情况下直接发送twisted.internet.error.TimeoutError_Python_Python 2.7_Scrapy_Timeout - Fatal编程技术网

Python 如何在不请求的情况下直接发送twisted.internet.error.TimeoutError

Python 如何在不请求的情况下直接发送twisted.internet.error.TimeoutError,python,python-2.7,scrapy,timeout,Python,Python 2.7,Scrapy,Timeout,我有一个包含数千个URLs的数据库,我用一个蜘蛛抓取它们。例如,100URLs可以具有相同的域: http://notsame.com/1 http://notsame2.com/1 http://dom.com/1 http://dom.com/2 http://dom.com/3 ... 问题是,有时网页/域不返回任何内容,因此我认为您构建TimeoutProcessMiddleware的想法是正确的。更具体地说,我将把它构建为一个下载中间件 下载中间件可以处理每个传出的请求以及每个传入的

我有一个包含数千个
URL
s的数据库,我用一个蜘蛛抓取它们。例如,100
URL
s可以具有相同的域:

http://notsame.com/1
http://notsame2.com/1
http://dom.com/1
http://dom.com/2
http://dom.com/3
...

问题是,有时网页/域不返回任何内容,因此我认为您构建
TimeoutProcessMiddleware
的想法是正确的。更具体地说,我将把它构建为一个下载中间件

下载中间件可以处理每个传出的请求以及每个传入的响应。。。而且。。。它还可以处理在处理请求/响应时弹出的每个异常。详情:

所以我要做的(在未经测试的要点中,可能需要一些微调):


非常感谢。只有一件事。在def err(self)中,我处理超时的URL,因此如果我只是强制超时错误而不是引发IgnoreRequest(),会更简单。可能吗?我不能直接提出twisted.internet.error.TimeoutError吗?我想按时间安排的方式处理时间安排域的所有URL。我已使用您的代码编辑了我的代码。您对此有何看法?根据文档,我们必须在
处理请求
中提出
忽略请求
。。。您可以尝试使用
TimeoutError
,但我不知道会发生什么。同样在我的示例中,中间件进行簿记,您可以避免在spider中使用err回调。
class TimeoutProcessMiddleware:
     _timeouted_domains = set()

    def process_request(request,spider):
        domain = get_domain(request.url)
        if domain in _timeouted_domains:
            return twisted.internet.error.TimeoutError
        return request

    def process_response(request, exception, spider):
        # left out the code for counting timeouts for clarity
        if is_timeout_exception(exception):
            self._timeouted_domains.add(get_domain(request.url))
class TimoutProcessMiddleware(scrapy.downloadermiddlewares.DownloaderMiddleware):
    _timeouted_domains = set()

    def process_request(request, spider):
        domain = get_domain(request.url)
        if domain in self._timeouted_domains:
            raise IgnoreRequest():

    def process_response(request, exception, spider):
        # left out the code for counting timeouts for clarity
        if is_timeout_exception(exception):
            self._timeouted_domains.add(get_domain(request.url))