废LinkExtractor和设置深度限制不起作用?

2024-09-28 01:31:38 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我传递了一个start_url,这是一页新闻文章(例如cnn.com)。我不想把这篇文章的内容摘录出来。为此,我使用^{}和以下规则:

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 

我已经启用了^{}并设置了^{}。在

但是,我仍然可以从各个文章页面中抓取到与regexToMatchArticleUrls匹配的链接,因为它们是指向同一网站其他部分的链接(我不能使regex更具限制性)。在

但是,为什么这些链接在DEPTH_LIMIT=1时被爬网呢?是因为DEPTH_LIMIT重置从LinkExtractor提取的每个链接,即文章页面的url?有没有一种方法可以使DEPTH_LIMIT工作,或者扩展{}来不爬网文章页面上的链接?谢谢!在


Tags: comurlparse链接article文章page页面
1条回答
网友
1楼 · 发布于 2024-09-28 01:31:38

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

不幸的是,默认情况下,crawspider不会在一个请求到下一个请求之间保留这个meta属性。在

这可以通过使用spider中间件(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中包含此中间件:

^{pr2}$

相关问题 更多 >

    热门问题