node.js - 用 Cheerio 嵌套每个循环选择
问题描述
我试图用 Cheerio 做一个嵌套的每个循环,选择我的 Cheerio 选择两次。我以这种方式编写代码是因为我想迭代父选择的数量,同时进行二次选择。
我的第二个每个循环都没有找到任何元素。我也尝试过创建一个新的 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
});
});
解决方案
能够使其与以下内容一起使用。无论出于何种原因,我不得不重新选择每个循环的子元素以获取其内部文本。对于父元素,我只能在参数上调用 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
});
});
});
推荐阅读
- mongodb - 如何将多张图片上传到 Deno?
- c++ - 按字母顺序对结构内数组变量中的名称进行排序
- powershell - 创建指向 UNC 路径的符号链接不起作用?
- android-studio - 如何从颤振的 android studio 构建 apk
- matlab - MATLAB 如何在我当前的程序中添加 surf 函数
- javascript - 如何将多个复选框的状态保存到后端?
- python - 如何在我的 CSV 文件中选择某个数据点并绘制所有值为 + 或 - 1 的值?
- r - R 中的动态规划 - 仓库位置之间距离的算法
- objective-c - 调用 CGContextDrawImage 后内存泄漏
- python - 如何使用 Python 从 JSON 数组对象打印集合