You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scrapy爬取container类下锚点遇问题:仅获第一个锚点,新手求助

解决Scrapy爬取面包屑锚点的问题

问题原因

你用response.css('.breadcrumbs div.container a').getall()只拿到第一个锚点,大概率是页面动态渲染导致的——原始静态HTML里只有第一个<a>标签,剩下的是通过JavaScript加载的,Scrapy默认只会抓取初始的静态内容。

解决方案

1. 渲染页面获取动态内容(需安装playwright)

如果你的Scrapy版本支持,给请求加上playwright元参数,让页面执行JS后再抓取:

def start_requests(self):
    yield scrapy.Request(url=你的目标URL, callback=self.parse, meta={'playwright': True})

def parse(self, response):
    # 现在能拿到所有锚点了
    all_anchors = response.css('.breadcrumbs div.container a').getall()
    # 取第三个锚点(索引从0开始,所以是[2])
    third_anchor = all_anchors[2] if len(all_anchors) >=3 else None
    print(third_anchor)

2. 直接请求数据接口

打开浏览器F12进入Network面板,刷新页面找加载面包屑的API接口,直接请求接口拿数据,这种方式比渲染页面更高效。

3. 修正选择器(如果页面是静态的)

如果页面是纯静态的,试试更精准的选择器:

# CSS选择器
all_anchors = response.css('div.container > a').getall()
# 或者XPath选择器
all_anchors = response.xpath('//div[@class="container"]/a').getall()

直接获取第三个锚点的写法

不需要先拿所有锚点,直接用nth-child选择器定位第三个:

# 获取第三个锚点的文本
third_text = response.css('div.container > a:nth-child(3)::text').get()
# 获取第三个锚点的链接
third_href = response.css('div.container > a:nth-child(3)::attr(href)').get()

内容的提问来源于stack exchange,提问作者Syed Zohaib Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:15:43