Scrapy LinkExtractor - 限制每个URL抓取的页面数

时间:2015-12-24 12:23:57

标签: python web-crawler scrapy limit

我试图限制Scrapy中CrawlSpider中每个URL的已爬网页面数。我有一个start_urls列表,我想设置每个URL中被抓取的页数限制。达到限制后,蜘蛛应移至下一个start_url。

我知道设置上有DEPTH_LIMIT参数,但这不是我要找的。

任何帮助都会有用。

以下是我目前的代码:

class MySpider(CrawlSpider):
    name = 'test'
    allowed_domains = domainvarwebsite
    start_urls = httpvarwebsite

    rules = [Rule(LinkExtractor(),
             callback='parse_item',
             follow=True)
            ]

    def parse_item(self, response):
        #here I parse and yield the items I am interested in.

修改

我试图实现这一点,但我得到exceptions.SyntaxError: invalid syntax (filter_domain.py, line 20)。对于发生了什么的任何想法?

再次感谢。

filter_domain.py

import urlparse
from collections import defaultdict
from scrapy.exceptions import IgnoreRequest

class FilterDomainbyLimitMiddleware(object):
def __init__(self, domains_to_filter):
    self.domains_to_filter = domains_to_filter
    self.counter = defaultdict(int)

@classmethod
def from_crawler(cls, crawler):
    settings = crawler.settings
    spider_name = crawler.spider.name
    max_to_filter = settings.get('MAX_TO_FILTER')
    o = cls(max_to_filter)
    return o

def process_request(self, request, spider):
    parsed_url = urlparse.urlparse(request.url)
    (LINE 20:) if self.counter.get(parsed_url.netloc, 0) < self.max_to_filter[parsed_url.netloc]):
        self.counter[parsed_url.netloc] += 1
    else:
        raise IgnoreRequest()

settings.py

MAX_TO_FILTER = 30

DOWNLOADER_MIDDLEWARES = {
    'myproject.filter_domain.FilterDomainbyLimitMiddleware' :400,

}

1 个答案:

答案 0 :(得分:2)

Scrapy不直接提供此功能,但您可以创建自定义中间件,如下所示:

import urlparse
from collections import defaultdict
from scrapy.exceptions import IgnoreRequest

class FilterDomainbyLimitMiddleware(object):
    def __init__(self, domains_to_filter):
        self.domains_to_filter = domains_to_filter
        self.counter = defaultdict(int)

    @classmethod
    def from_crawler(cls, crawler):
        settings = crawler.settings
        spider_name = crawler.spider.name
        domains_to_filter = settings.get('DOMAINS_TO_FILTER')
        o = cls(domains_to_filter)
        return o

    def process_request(self, request, spider):
        parsed_url = urlparse.urlparse(request.url)
        if parsed_url.netloc in self.domains_to_filter:
            if self.counter.get(parsed_url.netloc, 0) < self.domains_to_filter[parsed_url.netloc]):
                self.counter[parsed_url.netloc] += 1
            else:
                raise IgnoreRequest()

并在以下设置中声明DOMAINS_TO_FILTER

DOMAINS_TO_FILTER = {
    'mydomain': 5
}

仅接受来自该域的5个请求。还要记住在指定的here

等设置中启用中间件