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

如何从Cheerio选择结果中获取第二个或第三个子元素的文本?

Cheerio 获取指定位置元素文本的方法

针对你的需求,Cheerio 提供了多种直接获取第N个元素文本的方式:

方法1:使用eq()方法

eq()接收从0开始的索引参数,精准定位目标元素:

// 获取第二个<li>的文本(索引为1)
const secondText = results.eq(1).text();
// 获取第三个<li>的文本(索引为2)
const thirdText = results.eq(2).text();

方法2:数组下标访问

Cheerio 对象支持像数组一样通过下标取值,注意取下标后得到的是原生DOM节点,需要用$()包装后再调用text():

// 获取第二个<li>的文本
const secondText = $(results[1]).text();
// 获取第三个<li>的文本
const thirdText = $(results[2]).text();

方法3:直接用选择器定位

也可以在find阶段通过:nth-child()选择器指定位置(该选择器从1开始计数):

// 获取第二个<li>的文本
const secondText = item.find('ul li:nth-child(2)').text();
// 获取第三个<li>的文本
const thirdText = item.find('ul li:nth-child(3)').text();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:13:08