我有一个链接列表,我必须模拟使用CasperJS点击.他们都共享同一个班级.
但是this.click('.click-me')只使用第一个链接上的点击.
点击所有链接的正确方法是什么?我想也许我应该尝试获取链接的数量evaluate()然后使用for循环.但是,如果我使用evaluate()链接的数量,我必须使用消息进行通信,这似乎很复杂.
有没有更好的办法?
Tys*_*ero 15
我最终使用nth-child()选择器来完成此任务.这是如何做...
页:
<ul id="links">
<li><a href="#1">1</a></li>
<li><a href="#2">2</a></li>
<li><a href="#3">3</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)
脚本:
casper.then(function() {
var i = 1;
this.repeat(3, function() {
this.click('#links li:nth-child(' + i + ') a');
i++;
});
});
Run Code Online (Sandbox Code Playgroud)
你显然不必使用重复,但任何迭代技术都应该有效.
正如CasperJS ML和记录中所提出的,这里有一个可能的实现clickWhileSelector:
var casper = require('casper').create();
casper.clickWhileSelector = function(selector) {
return this.then(function() {
if (this.exists(selector)) {
this.echo('found link: ' + this.getElementInfo(selector).tag);
this.click(selector);
return this.clickWhileSelector(selector);
}
return this.echo('Done.').exit();
});
}
casper.start().then(function() {
this.page.content =
'<html><body>' +
'<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 1</a>' +
'<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 2</a>' +
'<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 3</a>' +
'</body></html>';
});
casper.clickWhileSelector('a').run();
Run Code Online (Sandbox Code Playgroud)
这给了:
$ casperjs c.js
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 1</a>
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 2</a>
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 3</a>
Done.
Run Code Online (Sandbox Code Playgroud)