繁体   English   中英

点击网页Casperjs上的所有链接

[英]Click on all the links on a webpage Casperjs

我是javascript和casperjs的初学者。

我试图单击页面上找到的所有链接。

 casper.then(function() {
    Array.prototype.forEach.call(__utils__.findAll('a'), function(e) {
        this.click('a');
        console.log('clicked ok, new location is ' + this.getCurrentUrl());
        casper.back();
        console.log('clicked ok, new location is ' + this.getCurrentUrl());
    });
});

这将很有用:

casper.then(function() {
    Array.prototype.forEach.call(__utils__.findAll('a'), function(e) {
        e.click();
        console.log('clicked ok, new location is ' + this.getCurrentUrl());
        casper.back();
        console.log('clicked ok, new location is ' + this.getCurrentUrl());
    });

您在这里混淆了很多东西:

  • __utils__是clientutils模块,仅在页面上下文中(在casper.evaluate()内部casper.evaluate()可用。 页面上下文是沙盒,因此您不能使用外部变量或将DOM节点传递到外部。

  • CasperJS是按步骤组织的,但并非所有功能都是步骤功能。 casper.click()是阻止点击的调用,但是casper.back()是异步的。

  • casper.click()单击与选择器匹配的第一个元素,但由于每次迭代选择器始终相同,因此每次都会单击相同的元素。 您必须跟踪已经单击的元素。 这可以在页面上下文中完成,但是您就不casper.click()使用casper.click()了,或者可以通过XPath表达式来实现。

示例代码:

var x = require('casper').selectXPath;
casper.then(function() {
    var count = this.getElementsInfo("a").length;
    for(var i = 1; i <= count; i++){
        this.thenClick(x('(//a)['+i+']'))
            .then(function(){
                console.log('clicked ok, new location is ' + this.getCurrentUrl());
            })
            .back()
            .then(function(){
                console.log('back to location ' + this.getCurrentUrl());
            });
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM