【问题标题】:Cheerio get element outer htmlCheerio 获取元素外部 html
【发布时间】:2017-09-07 23:27:42
【问题描述】:

我正在使用cheerio 在节点6.10.2 的服务器端解析html 文件。我需要获取文档正文中每个 div 的 outerHtml,我的代码是:

 /* const data is valid html document (type of string)*/
 const $ = cheerio.load(data);
 let pages = $('body > div').toArray();
 console.log(pages[0]); // Elements parsed correctly
 let htmlPages = pages.map(page => $(page).html());
 console.log(htmlPages[0]); // Here I have innerHtml, not outer...      

问题:我正在使用 innerHtml 获取字符串。 任何人都可以帮忙吗? ?

【问题讨论】:

    标签: javascript node.js dom


    【解决方案1】:

    将您的地图功能更改为

    let htmlPages = pages.map(page => $.html(page));
    

    根据docs

    【讨论】:

      【解决方案2】:

      如果您无法轻松访问原始 $ 对象,以下方法也可以使用

      function outerHTML (element) {
          var index = element.index();
          var parent = element.parent().clone();
          var child = parent.children()[index];
          parent.empty();
          parent.append(child);
          return parent.html();
      }
      

      【讨论】:

      • 对我不起作用,我只是在 index() 上收到一个错误,它不是函数:休斯顿我们有问题:TypeError: element.index is not a function at outerHTML (C :\xxxxx\cafe\locators\crawler\scanner.js:77:23) 在 GetElementContent (C:\xxxxx\cafe\locators\crawler\scanner.js:45:15) 在 Node.GetElementContent.$.children.each (C:\xxxxx\cafe\locators\crawler\scanner.js:67:7) 在 initialize.exports.each (C:\xxxxx\node_modules\cheerio\lib\api\traversing.js:300:24) 在 GetElementContent (C:\xxxxx\cafe\locators\crawler\scanner.js:62:27)
      • 这确实有效:function outerHTML(element) { $(element).each(function(index, elem) { var $this = $(this); console.log($.html($这)); }); };
      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      相关资源
      最近更新 更多