【问题标题】:casperjs: Howto get links that contain text?casperjs:如何获取包含文本的链接?
【发布时间】:2017-09-12 09:57:31
【问题描述】:

我尝试这样做:但看起来不起作用

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() 中使用它吗?

【问题讨论】:

    标签: casperjs


    【解决方案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.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"
    ]
    

    【讨论】:

      猜你喜欢
      • 2013-01-29
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 1970-01-01
      • 1970-01-01
      • 2012-05-27
      相关资源
      最近更新 更多