You need to enable JavaScript to run this app. Scrapy爬取锚点链接与同页Title/H1元素 实现逐行CSV导出的方法
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy爬取锚点链接与同页Title/H1元素 实现逐行CSV导出的方法

Scrapy导出CSV时拆分嵌套链接为独立行的实现方案

当前实现的核心问题是:代码将同页面下所有锚文本、链接地址作为平行列表字段塞入单条yield字典,Scrapy的默认CSV导出器只会将列表内容序列化为字符串存入单个单元格,无法实现拆行效果。

核心实现逻辑

要达到单条链接占独立行、复用页面公共维度字段的效果,不需要改动Scrapy的导出管道,只需要在爬虫的解析阶段做两个调整:

  • 提前将所有属于当前页面的单值维度字段组装成公共模板,这类字段对当前页面拆分出的所有链接行取值完全一致
  • 逐一遍历页面内所有a标签,对每个a标签单独生成一条独立的字典,复用公共模板的字段值,填入当前a标签对应的锚文本、链接地址,再单独yield

关键注意:绝对不要修改同一个公共字典后重复yield,Python的字典是可变引用类型,如果不生成独立字典副本,最终导出的所有链接行都会被覆盖为最后一个a标签的值


改造后可直接运行的完整代码

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import Rule, CrawlSpider


class InseevSpiderSpider(scrapy.spiders.CrawlSpider):
    name = 'ExampleScraper'
    allowed_domains = ['example.com']
    start_urls = ['https://www.example.com/']
    rules = (
        Rule(LinkExtractor(allow_domains=['example.com']), follow=True, callback="parse_item"),
        Rule(LinkExtractor(deny=('.png', ))),
    )

    def parse_item(self, response):
        # 计算当前页面的公共维度字段
        address = response.url
        count_address = len(address)
        content_type = response.headers.get('Content-Type', b'').decode()
        status_code = response.status
        # 给所有可能为空的字段加兜底值,避免计算长度时抛类型错误
        title = response.xpath("//title/text()").extract_first() or ""
        count_title = len(title)
        description = response.xpath("//meta[@name='description']/@content").extract_first() or ""
        count_description = len(description)
        keywords = response.xpath("//meta[@name='keywords']/@content").extract_first() or ""
        h1 = response.xpath('//h1//text()').extract_first() or ""
        h2 = response.xpath('//h2//text()').extract_first() or ""
        robot = response.xpath("//meta[@name='robots']/@content").extract_first() or ""
        download_time = response.meta.get('download_latency', 0)

        # 公共字段模板,所有链接行复用这部分的值
        common_item = {
            'Address': address,
            'Address count': count_address,
            'Content Type': content_type,
            'Status code': status_code,
            'Title': title,
            'Title count': count_title,
            'Meta description': description,
            'Meta description count': count_description,
            'Meta keywords': keywords,
            'H1': h1,
            'H2': h2,
            'Robot': robot,
            'Download time': download_time,
        }

        # 直接遍历a标签节点,从根源避免锚文本和链接错位
        all_a_tags = response.xpath('//a')
        for a_tag in all_a_tags:
            link_anchor = a_tag.xpath('./text()').extract_first() or ""
            raw_link_href = a_tag.xpath('./@href').extract_first() or ""
            # 过滤无实际意义的空链接
            if not raw_link_href.strip():
                continue
            # 生成独立的字典实例,避免引用覆盖
            current_item = common_item.copy()
            current_item['Link Anchor'] = link_anchor.strip()
            # 如果需要绝对路径可启用下面的urljoin转换
            # current_item['Link @href'] = response.urljoin(raw_link_href.strip())
            current_item['Link @href'] = raw_link_href.strip()
            yield current_item

常见踩坑说明

  • 锚文本与链接错位问题:原代码分开取所有a的text为列表、所有a的href为列表再做zip配对,一旦页面存在无文本、无href的a标签,两个列表长度就会不一致,导致配对错位。直接遍历a标签选择器节点,可以保证锚文本和href始终属于同一个a元素。
  • 空值报错问题:原代码对title等字段直接取列表后按索引取值,遇到无title的页面会直接触发索引越界错误,统一加空值兜底后可以稳定爬取。
  • 导出格式问题:经过改造后,每条yield的字典都是单值字段,Scrapy默认的CSV导出器可以直接按照预设列名整齐导出,不会出现单元格内嵌长列表的情况。

内容的提问来源于stack exchange,提问作者jmelm93

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.18 07:24:11