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

时间:2017-09-12 09:57:32

标签: casperjs

我尝试了这个:但是看起来没有工作

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 );

console.log似乎也不起作用:我可以在evaluate()中使用它吗?

1 个答案:

答案 0 :(得分:1)

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.logevaluate()内工作是正确的,因为它在网页的上下文中运行: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"
]