这是How to stop a loop when clicking asynchronously in CasperJS的附加问题
我尝试了这段代码
function execOnce(casper, i, max){
// end condition
if (i === max) {
return;
}
casper.wait(3000, function() {
var button = x('//*[@id="content"]/div[3]/a['+i+']');
if (!this.exists(button)) {
this.echo(i + " not available");
return;
}
this.thenClick(button, function (){
console.log('Searching dic');
words = words.concat(this.evaluate(getWords));
// recursive step
execOnce(this, i+1, max);
});
});
};
// start the recursive chain
casper.then(function(){
execOnce(this, 1, 200);
});
但是我发现我的目标网页索引的Xpath有迭代。
当到达 '//*[@id="mArticle"]/div[2]/a['11']'
时,下一个索引的 Xpath 变为 '//*[ @id="mArticle"]/div[2]/a['2']
(返回a['2'])
例如网页网址为“http://krdic.naver.com/search.nhn?query=%E3%85%8F%E3%85%8F&kind=keyword”
页面下方有[1][2][3][4][5][6][7][8][9][10][下一页]
当我单击下一页时,您可以看到
[Previous Page][11][12][13][14][15][16][17][18][19][20] [Next Page]
但是 [12] 的 Xpath 不是 //*[@id="content"]/div[3]/a[12]
---> 它是
//*[@id="content"]/div[3]/a[2]
所以我必须迭代function execOnce
,包括代码casper.wait(6000, function() {}
因为我的目标网站对查询非常敏感,所以我尽可能地放置“等待”代码..!
在这种情况下我可以使用这样的嵌套函数吗?
function execOnce(casper, i, max){
if (i === max) {
function execOnce(casper, i, max){
return;
}
...
最佳答案
XPath 非常具有表现力。例如,您可以根据链接文本而不是链接位置选择预期的页面链接 (//div[@class='paginate']/a[text()='5']
),但是在这种情况下,仅此一点对您没有多大帮助。
问题当然是该网站有辅助分页。您需要先进入下一个分页页面,然后才能单击下一个分页链接。
casper.wait(3000, function() {
var nextButton = x('//*[@id="content"]/div[3]/a[text()="'+i+'"]');
var lastPageNextButton = '.paginate > strong + a.next';
var button = nextButton;
if (this.exists(lastPageNextButton)) {
button = lastPageNextButton;
} else if (!this.exists(button)) {
this.echo(i + " not available");
return;
}
this.thenClick(button, function (){
console.log('Searching dic');
words = words.concat(this.evaluate(getWords));
// recursive step
execOnce(this, i+1, max);
});
});
关于javascript - 是否可以在 CasperJS 中进行 "for"循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32426015/