首页 > 解决方案 > 用 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
    });
  });

标签: node.jscheerio

解决方案


能够使其与以下内容一起使用。无论出于何种原因,我不得不重新选择每个循环的子元素以获取其内部文本。对于父元素,我只能在参数上调用 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
      });
    });
  });

推荐阅读