2015-09-06 98 views
0

這是How to stop a loop when clicking asynchronously in CasperJS是否有可能在CasperJS中創建「for」循環?

額外的問題,我想這代碼

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'](回[ '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]

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; 
     } 
     ... 
+0

呃......你的意思是......一次執行那些嵌套的函數代碼?? –

+0

非常感謝你 –

回答

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

我試過嵌套的功能代碼,它的工作原理!但你的代碼更美麗非常感謝你! –