Scrapy - LinkExtractor 和设置 DEPTH_LIMIT 不工作?

Scrapy - LinkExtractor & setting DEPTH_LIMIT not working?

所以我传入了一个 start_url,这是一页新闻文章(例如 cnn.com). But, I just want to extract the news article itself, I don't want to follow any links on article page. To do that, I'm using a CrawlSpider,规则如下:

rules = (
    Rule(LinkExtractor(allow=('regexToMatchArticleUrls',),
    deny=('someDenyUrls')), callback='parse_article_page'),
)

def parse_article_page(self,response): 
    #extracts the title, date, body, etc of article 

我启用了 scrapy.spidermiddlewares.depth.DepthMiddleware and set DEPTH_LIMIT = 1

但是,我仍然从恰好与 regexToMatchArticleUrls 匹配的个别文章页面抓取 links,因为它们是 links 到相同的其他部分网站(我不能使正则表达式更具限制性)。

但是,为什么 DEPTH_LIMIT=1 时这些 link 会被抓取?是不是因为从 LinkExtractor 中提取的每个 link 都会重置 DEPTH_LIMIT,即。文章页面网址?有没有办法让 DEPTH_LIMIT 工作或扩展 DepthMiddleware 以不抓取文章页面上的 link?谢谢!

为了让 DepthMiddleware 正常工作,meta 属性需要从一个请求传递到另一个请求,否则,depth 将在每个新请求后设置为 0。

不幸的是,默认情况下,CrawlSpider 不会从一个请求到下一个请求保留此元属性。

这可以通过使用蜘蛛中间件来解决(middlewares.py):

from scrapy import Request


class StickyDepthSpiderMiddleware:

    def process_spider_output(self, response, result, spider):
        key_found = response.meta.get('depth', None)
        for x in result:
            if isinstance(x, Request) and key_found is not None:
                x.meta.setdefault('depth', key_found)
            yield x

此外,不要忘记在您的 settings.py:

中包含此中间件
SPIDER_MIDDLEWARES = { '{your_project_name}.middlewares.StickyDepthSpiderMiddleware' : 100 }