【问题标题】:Load specific HTML by using cheerio in nodejs?在nodejs中使用cheerio加载特定的HTML?
【发布时间】:2016-06-05 09:06:03
【问题描述】:

我需要从给定的网页获取所有<a> 标签网址。而且我还需要避免在页眉和页脚标签之间使用<a> 标签。我正在加载正文标签 html 但没有标题标签。这是我的代码,但它不起作用。

var $ = cheerio.load(html);
$ = cheerio.load($('body').not('header'));

var links = $("a']");
links.each(function() {
    console.log($(this).attr('href'));
});

如果上面的代码有错误,请建议如何做到这一点?

【问题讨论】:

    标签: javascript html node.js cheerio


    【解决方案1】:

    Cheerio 的工作方式与 jQuery 类似。

    var $ = cheerio.load(html);
    var links = $('body').not('header').find('a');
    // $('body:not(header) a') may also work.
    
    links.each(function() {
        console.log(this.href);
    });
    

    【讨论】:

    • 这也不是删除标题标签
    • 您无需更改 DOM 即可避免检查标头。
    • var $=cheerio.load(body); var t = $('body'); t.children('header').remove(); t.children('footer').remove();变量 t = $.html(t); var $ =cheerio.load(t);我这样做了它的工作正常
    • 或者干脆不理我,没关系。
    【解决方案2】:

    我认为错误是因为您没有在第二次加载时加载 HTML。您正在加载 body 对象。你应该可以这样做:

    var $ = cheerio.load(html);
    $ = cheerio.load($('body').html());
    
    $('header').remove();
    
    console.log($.html());
    

    【讨论】:

    • 很抱歉。我一开始是在浏览器中测试的。这正在工作。
    【解决方案3】:

    我确实喜欢这个,现在它工作正常...谁能告诉我这是正确的方法吗?...

    var $ = cheerio.load(body);
    var t = $('body');
    t.children('header').remove();
    t.children('footer').remove();
    var t = $.html(t);
    var $ = cheerio.load(t);
    var links = $("a");
    links.each(function() {
        console.log($(this).attr('href'));
    });
    

    谢谢,

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 2019-04-22
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 2020-01-02
      • 1970-01-01
      相关资源
      最近更新 更多