Skip to main content
 首页 » 编程设计

python之scrapy 只关注一个深度的外部链接

2025年02月15日6lyhabc

假设我正在抓取 foo.com。 foo.com 有几个指向自身的内部链接,还有一些外部链接,例如:

foo.com/hello 
foo.com/contact 
bar.com 
holla.com 

我希望 scrapy 抓取所有内部链接,但也只抓取外部链接的一个深度,例如我希望 scrapy 转到 bar.com 或 holla.com但我不希望它转到 bar.com 中的任何其他链接,所以只有一个深度。

这可能吗?这种情况下的配置是什么?

谢谢。

请您参考如下方法:

你可以让你的爬虫基于 CrawlSpider 类,并使用 Rule 和实现的 process_links 方法,你传递给 Rule 。该方法将在不需要的链接被关注之前过滤掉它们。来自documentation :

process_links is a callable, or a string (in which case a method from the spider object with that name will be used) which will be called for each list of links extracted from each response using the specified link_extractor. This is mainly used for filtering purposes.