我有一个CrawlSpider派生的蜘蛛。当url具有某种格式时,它会回调一个名为parse_item的函数。
rules = (
Rule(
LinkExtractor(
allow=('/whatever/', )
)
),
Rule(
LinkExtractor(
allow=('/whatever/detailpage/1234/')
),
callback='parse_item'
),
)我有一个状态only_new=True为我的蜘蛛。当这个状态被启用时,我不想抓取已经在我的数据库中的urls。
我想在请求完成之前检查url,因为当我有5个新的详细页面我想抓取,但1000个详细页面我不想抓取,我想发送5个请求而不是1000个。
但是在回调函数中,请求已经完成了。我想做一些类似以下的事情:
rules = (
(...)
Rule(
LinkExtractor(
allow=('/whatever/detailpage/1234/')
),
callback_before_request='check_if_request_is_nessesary'
),
)
def check_if_request_is_nessesary(spider, url):
if spider.only_new and url_exists_in_database():
raise IgnoreRequest
else:
do_request_and_call_parse_item(url)有没有可能使用中间件或其他什么东西?
发布于 2014-12-26 05:17:45
您正在寻找process_links attribute for the Rule --它允许您指定一个可调用的名称或方法名,用于过滤LinkExtractor返回的Link对象列表。
您的代码将如下所示:
rules = (
(...)
Rule(
LinkExtractor(
allow=('/whatever/detailpage/1234/')
),
process_links='filter_links_already_seen'
),
)
def filter_links_already_seen(self, links):
for link in links:
if self.only_new and url_exists_in_database(link.url):
continue
else:
yield linkhttps://stackoverflow.com/questions/27649731
复制相似问题