【问题标题】:Is it possible to make "for" loop in CasperJS?是否可以在 CasperJS 中创建“for”循环?
【发布时间】:2015-09-06 16:57:23
【问题描述】:

是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] [Next Page]

当我点击下一页你可以看到

 [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;
        }
        ...

【问题讨论】:

  • 呃……你的意思是……执行那些嵌套的函数代码一次??

标签: javascript xpath iteration casperjs


【解决方案1】:

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);
    });
});

【讨论】:

  • 我尝试了嵌套函数代码,它可以工作!但是您的代码更漂亮非常感谢您!
猜你喜欢
  • 1970-01-01
  • 2018-04-10
  • 2021-04-09
  • 2020-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多