【问题标题】:Nested each loop selections with Cheerio用 Cheerio 嵌套每个循环选择
【发布时间】:2019-01-24 05:06:19
【问题描述】:

我正在尝试使用 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
    });
  });

【问题讨论】:

    标签: node.js cheerio


    【解决方案1】:

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

    【讨论】:

    • 是的,您在这些 HOF 中迭代 js dom 元素而不是 Cheerio 对象。因此,例如 elem.innerText 会起作用。
    • 什么是 HOF? @pguardiario
    • 高阶函数如each, map, reduce, filter, forEach等...
    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    相关资源
    最近更新 更多