如何 select in cheerio

How to select in cheerio

我想 select div 中索引 2 的 Html with cheerio:

<div>..</div>
<div>..</div>
<div>..</div> //div index 2
<div>..</div>

我该怎么做?

使用cheerio的get方法

.get( [i] )

检索与 Cheerio 对象匹配的 DOM 个元素。如果指定了索引,则检索与 Cheerio 对象匹配的元素之一:

$('div').get(2)

您可以使用伪元素 :nth-of-type(number) 来查找 div。你的选择器看起来像这样 div:nth-of-type(3) 你可以用同样的方式在 cheerio 中使用 $('div:nth-of-type(3)')

像这样的东西应该可以工作:

const cheerio = require('cheerio');

const $ = cheerio.load('<div></div><div></div><div></div><div></div>');

$('div:nth-child(3)');

请记住 nth-child 使用基于 1 的索引。