代码之家  ›  专栏  ›  技术社区  ›  yarek

casperjs:如何获取包含文本的链接?

  •  1
  • yarek  · 技术社区  · 8 年前

    function getLinks(containText) {
        return casper.evaluate(function(containText) {
            var links = document.querySelectorAll('a');
            return Array.prototype.map.call(links, function (e) {
                var href = e.getAttribute('href');
                console.log(href);
                if (href.indexOf(containText) !== -1) {
                    return href;
                }
            });
        })
    }
    links = getLinks('intermediary');
    require('utils').dump(links );
    

    1 回复  |  直到 8 年前
        1
  •  1
  •   davejagoda    8 年前
    var casper = require('casper').create();
    
    function getLinks(containText) {
        var links = document.querySelectorAll('a');
        return Array.prototype.map.call(links, function(e) {
            return e.getAttribute('href');
        }).filter(function(e) {
            return e.indexOf(containText) !== -1;
        });
    }
    
    casper.start('file:///tmp/test.html', function() {
        var links = this.evaluate(getLinks, 'intermediary');
        require('utils').dump(links);
    });
    
    casper.run();
    

    你说得对 console.log 不会在内部工作 evaluate() 由于它在网页的DOM上下文中运行: http://docs.casperjs.org/en/latest/modules/casper.html#casper-evaluate

    /tmp/test.html 要显示过滤效果,请执行以下操作:

    <html>
      <head>
        <title>test</title>
      </head>
      <body>
        <p>Here are some example pages.</p>
        <p><a href="intermediary">a link</a></p>
        <p><a href="click">click</a></p>
        <p><a href="this contains the string intermediary in it">other link</a></p>
        <p><a href="this does not contain string">yet another link</a></p>
      </body>
    </html>
    

    和输出:

    [
        "intermediary",
        "this contains the string intermediary in it"
    ]