javascript - 是否可以在 CasperJS 中进行 "for"循环?

标签 javascript xpath iteration casperjs

这是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][下一页]

enter image description here

当我单击下一页时,您可以看到

 [Previous Page][11][12][13][14][15][16][17][18][19][20] [Next Page]

enter image description here

但是 [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/

相关文章:

javascript - 如何使用jquery获取TD值

javascript - Javascript 中嵌套 if 语句(函数内)的问题

javascript - 操作 X 和 Y 属性 Unity2D-Javascript

java - 是否有支持迭代时并发修改的列表集合?

php - 文件结构到多维数组

javascript - 是否有一种内置的方法来遍历对象的属性?

javascript - 在除元素之外的 body 上应用模糊

XPATH 过滤无标签子项

c# - 如何在 Linq-to-XML 中按路径查找 XML 节点

javascript - 如何使用xPath选择多个元素?