
本教程旨在解决 scrapy 爬虫在处理页面内部嵌套链接时常见的重复数据、数据缺失和低效分页等问题。文章深入分析了 `dont_filter=true` 的滥用、分页逻辑错误以及不当的嵌套请求数据传递方式,并提供了基于 scrapy 最佳实践的解决方案。通过优化去重、分页策略和数据项生成机制,确保爬取过程的效率与数据输出的完整性,并提供清晰的代码示例。
在使用 Scrapy 爬取复杂网站时,尤其当页面包含多层嵌套链接(如受害者、恶意软件、威胁来源等列表,且需要进一步访问这些链接获取详细信息)时,常常会遇到数据重复、数据丢失或爬取效率低下的问题。这些问题通常源于对 Scrapy 核心机制的误解或不当使用。本教程将详细分析这些常见陷阱,并提供一套健壮的解决方案。
在处理内部链接和分页时,以下是导致上述问题的几个主要原因:
dont_filter=True 参数会禁用 Scrapy 内置的请求去重过滤器。Scrapy 默认会跟踪所有已访问的 URL,并避免重复发送请求。当 dont_filter=True 被广泛使用时,爬虫会重复访问相同的页面,导致:
原始代码在 parse 方法中,每次都会获取所有分页链接,并为它们全部发送请求。这种做法的问题在于:
当需要从多个嵌套链接(例如,从主文章页面获取受害者链接,然后访问受害者页面获取详细信息)中聚合数据来构建一个完整的数据项时,原始代码采用了一种容易出错的数据传递和生成方式:
为了构建一个高效、健壮且数据完整的 Scrapy 爬虫,我们应遵循以下最佳实践:
除非有特殊需求(如需要绕过缓存重新下载页面),否则应避免使用 dont_filter=True。Scrapy 的调度器会确保每个 URL 只被请求一次,这对于避免重复数据和提高效率至关重要。
分页处理应遵循“只请求下一页”的原则。在 parse 方法中,找到当前页的“下一页”链接,并只为这一个链接发送请求。
# 示例:优化后的分页逻辑
def parse(self, response):
# ... 其他链接处理 ...
# 找到当前页的下一页链接
# 假设当前页的<li>有特定类名,下一页是其兄弟元素
current_page = response.css('li.wpv_page_current')
if next_page_link := current_page.xpath("./following-sibling::li/a/@href").get():
# 使用 response.urljoin 处理相对路径
yield scrapy.Request(response.urljoin(next_page_link), callback=self.parse)一个数据项(item)应该只在它所有必要字段都已收集完整时才被 yield。这意味着不能在中间回调函数中 yield 不完整的数据。
根据数据提取的需求,处理嵌套链接有两种主要策略:
策略一:父页面一次性提取所有相关链接及文本 (简化数据聚合)
如果目标仅仅是从主页面上提取所有相关子链接的 URL 和其对应的文本(而不是深入爬取每个子链接的详细内容),那么可以在主页面的解析回调中一次性完成所有数据的提取。这种方法避免了复杂的请求链,是最直接和高效的。
# 示例:策略一 - 在 parse_icsstrive 中直接提取所有相关信息
def parse_icsstrive(self, response):
# 提取主页面的标题、发布日期等
title = response.xpath('//h1[@class="entry-title"]/text()').get()
# 提取受害者、恶意软件、威胁来源的链接和名称
victims_links = response.xpath("//div[h3[text()='Victims']]//li/a/@href").getall()
victims_names = response.xpath("//div[h3[text()='Victims']]//li//text()").getall() # 提取所有文本,可能需要进一步清洗
malware_links = response.xpath("//div[h3[text()='Type of Malware']]//li/a/@href").getall()
malware_names = response.xpath("//div[h3[text()='Type of Malware']]//li//text()").getall()
threat_source_links = response.xpath("//div[h3[text()='Threat Source']]//li/a/@href").getall()
threat_source_names = response.xpath("//div[h3[text()='Threat Source']]//li/a/text()").getall()
# 构建并yield完整的数据项
yield {
"title": title,
"victims_names": victims_names,
"victims_links": victims_links,
"malware_names": malware_names,
"malware_links": malware_links,
"threat_source_names": threat_source_names,
"threat_source_links": threat_source_links,
# ... 其他字段 ...
}这种策略是问题答案中提供的解决方案所采用的,它大大简化了逻辑,避免了多层嵌套请求带来的复杂性。
策略二:正确构建嵌套请求链以深度爬取 (复杂数据聚合)
如果确实需要访问每个嵌套链接(如 victims_url, malwares_urls, threat_source_urls)以提取其详细内容,并将这些内容聚合到同一个主数据项中,那么需要更精细地管理请求链和数据传递。
# 示例:策略二 - 深度爬取子链接内容(概念性代码,需根据实际页面结构调整)
class IcsstriveSpider(scrapy.Spider):
name = "icsstrive_deep"
start_urls = ['https://icsstrive.com/']
baseUrl = "https://icsstrive.com"
def parse(self, response):
# 爬取主文章链接
for link in response.css('div.search-r-title a::attr(href)').getall():
yield response.follow(link, self.parse_icsstrive_main)
# 分页逻辑 (同前述优化)
current_page = response.css('li.wpv_page_current')
if next_page_link := current_page.xpath("./following-sibling::li/a/@href").get():
yield scrapy.Request(response.urljoin(next_page_link), callback=self.parse)
def parse_icsstrive_main(self, response):
# 提取主文章的基本信息
item_data = {
"title": response.xpath('//h1[@class="entry-title"]/text()').get(),
"published": response.xpath('//p[@class="et_pb_title_meta_container"]/span/text()').get(),
# ... 其他主文章字段 ...
"victims_details": [],
"malware_details": [],
"threat_source_details": [],
}
victims_urls = response.xpath('//div[@class="et_pb_text_inner"]/h3[text()="Victims"]/following-sibling::div/ul/li/a/@href').getall()
malwares_urls = response.xpath('//div[@class="et_pb_text_inner"]/h3[text()="Type of Malware"]/following-sibling::div/ul/li/a/@href').getall()
threat_source_urls = response.xpath('//div[@class="et_pb_text_inner"]/h3[text()="Threat Source"]/following-sibling::div/ul/li/a/@href').getall()
# 计数器,用于判断所有子请求是否完成
total_sub_requests = len(victims_urls) + len(malwares_urls) + len(threat_source_urls)
# 如果没有子链接,直接yield
if total_sub_requests == 0:
yield item_data
return
# 为每个受害者链接发送请求
for url in victims_urls:
yield scrapy.Request(
url,
callback=self.parse_victim_detail,
cb_kwargs={'item_data': item_data, 'total_sub_requests': total_sub_requests, 'current_sub_requests': 0}
)
# 为每个恶意软件链接发送请求
for url in malwares_urls:
yield scrapy.Request(
url,
callback=self.parse_malware_detail,
cb_kwargs={'item_data': item_data, 'total_sub_requests': total_sub_requests, 'current_sub_requests': 0}
)
# 为每个威胁来源链接发送请求
for url in threat_source_urls:
yield scrapy.Request(
url,
callback=self.parse_threat_source_detail,
cb_kwargs={'item_data': item_data, 'total_sub_requests': total_sub_requests, 'current_sub_requests': 0}
)
def _check_and_yield(self, item_data, total_sub_requests, current_sub_requests):
# 每次子请求完成时,递增计数器
current_sub_requests += 1
# 如果所有子请求都已完成,则yield最终数据项
if current_sub_requests == total_sub_requests:
yield item_data
return current_sub_requests # 返回更新后的计数器
def parse_victim_detail(self, response, item_data, total_sub_requests, current_sub_requests):
victim_detail = {
"title": response.xpath('//h1[@class="entry-title"]/text()').get(),
"description": response.xpath('//div[@class="et_pb_text_inner"]/p/text()').get(),
"url": response.url
}
item_data['victims_details'].append(victim_detail)
current_sub_requests = yield from self._check_and_yield(item_data, total_sub_requests, current_sub_requests)
# 注意:这里需要一个机制来正确更新和传递 current_sub_requests,
# 实际生产中通常会使用 Scrapy Item Pipelines 或更复杂的请求管理来聚合数据。
# 简单示例中,每次回调都会有独立的 current_sub_requests 副本,需要特殊处理。
# 更健壮的方法是使用 Item Pipeline 在所有相关请求完成后合并数据。
# 或者在 cb_kwargs 中传递一个可变对象(如列表或字典),并在其中维护计数。
def parse_malware_detail(self, response, item_data, total_sub_requests, current_sub_requests):
malware_detail = {
"title": response.xpath('//h1[@class="entry-title"]/text()').get(),
"description": response.xpath('//div[@class="et_pb_text_inner"]/p/text()').get(),
"url": response.url
}
item_data['malware_details'].append(malware_detail)
current_sub_requests = yield from self._check_and_yield(item_data, total_sub_requests, current_sub_requests)
def parse_threat_source_detail(self, response, item_data, total_sub_requests, current_sub_requests):
threat_source_detail = {
"title": response.xpath('//h1[@class="entry-title"]/text()').get(),
"description": response.xpath('//div[@class="et_pb_text_inner"]/p/text()').get(),
"url": response.url
}
item_data['threat_source_details'].append(threat_source_detail)
current_sub_requests = yield from self._check_and_yield(item_data, total_sub_requests, current_sub_requests)注意事项:上述策略二中的 _check_and_yield 和 current_sub_requests 计数器在 Scrapy 的异步模型中,直接通过 cb_kwargs 传递可变计数器并期望其在不同回调间共享状态是复杂的。更推荐的做法是:
以下是根据上述最佳实践和问题答案中的简化方案,优化后的 Scrapy Spider 代码。此代码采用策略一,即在主文章页面一次性提取所有受害者、恶意软件和威胁来源的链接及名称,不进行深度嵌套爬取。
import scrapy
class IcsstriveSpider(scrapy.Spider):
name = "icsstrive"
start_urls = ['https://icsstrive.com/']
base_url = "https://icsstrive.com" # 更名为 base_url,符合PEP8
def parse(self, response):
"""
解析主页或分页页面,提取文章链接并处理分页。
"""
# 提取当前页面所有文章链接,并跟随进入 parse_icsstrive 方法
for link in response.css('div.search-r-title a::attr(href)').getall():
yield response.follow(link, self.parse_icsstrive)
# 优化分页逻辑:只查找并请求下一页以上就是Scrapy 高效内部链接爬取与数据整合指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号