单击网页 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()
内)。页面上下文是沙盒化的,因此您不能使用外部变量或将 DOM 节点传递到外部。
CasperJS 是按步骤组织的,但并非所有函数都是步骤函数。 casper.click()
是阻塞点击调用,但 casper.back()
是异步的。
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());
});
}
});
我是 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()
内)。页面上下文是沙盒化的,因此您不能使用外部变量或将 DOM 节点传递到外部。CasperJS 是按步骤组织的,但并非所有函数都是步骤函数。
casper.click()
是阻塞点击调用,但casper.back()
是异步的。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());
});
}
});