使用 Cheerio 嵌套每个循环选择
Nested each loop selections with Cheerio
我正在尝试使用 Cheerio 进行嵌套的每个循环,选择我的 Cheerio 选择两次。我以这种方式编写代码,因为我想在进行二次选择时迭代父选择的数量。
我的第二个each循环没有找到任何元素。我还尝试创建一个新的 cheerio $$
构造函数并将 html 馈入其中,但这也失败了。
$(selector1).each(function (i, el) {
j++;
// logging html is showing several p elements
console.log($(this).html());
$(this).find('p').each((k, elem) => {
// but this loop is not finding any elements
// $(elem).text() returns null
});
});
能够让它与以下内容一起使用。无论出于何种原因,我不得不重新选择每个循环的子元素以获取其 innerText。对于父元素,我只能在参数上调用 text()。
const $ = cheerio.load(res);
const data = [];
$(selector1).each((i, el) => {
j++;
$(el).find('p').each((k, elem) => {
// i had to reselect $(elem) here rather than just use elem.text()
data.push({
text: $(elem).text(),
post: j
});
});
});
我正在尝试使用 Cheerio 进行嵌套的每个循环,选择我的 Cheerio 选择两次。我以这种方式编写代码,因为我想在进行二次选择时迭代父选择的数量。
我的第二个each循环没有找到任何元素。我还尝试创建一个新的 cheerio $$
构造函数并将 html 馈入其中,但这也失败了。
$(selector1).each(function (i, el) {
j++;
// logging html is showing several p elements
console.log($(this).html());
$(this).find('p').each((k, elem) => {
// but this loop is not finding any elements
// $(elem).text() returns null
});
});
能够让它与以下内容一起使用。无论出于何种原因,我不得不重新选择每个循环的子元素以获取其 innerText。对于父元素,我只能在参数上调用 text()。
const $ = cheerio.load(res);
const data = [];
$(selector1).each((i, el) => {
j++;
$(el).find('p').each((k, elem) => {
// i had to reselect $(elem) here rather than just use elem.text()
data.push({
text: $(elem).text(),
post: j
});
});
});