2015-10-06 30 views
4

我試圖從幾個頁面的網站獲得幾個元素。我目前正在使用PhantomJS來完成這項工作,而且我的代碼幾乎可以工作,但問題是,即使(根據日誌)我的代碼似乎已經轉移到第二個頁面,我的代碼也會在第一頁上進行兩次擦除。如何進入下一頁刮在PhantomJS

下面的代碼:

var page = require('webpage').create(); 
page.viewportSize = { width: 1061, height: 1000 }; //To specify the window size 
page.open("website", function() { 

    function fetch_names(){ 
     var name = page.evaluate(function() { 
      return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){ 
       return name.getAttribute('href'); 
      }); 
     }); 
     console.log(name.join('\n')); 
     page.render('1.png'); 
     window.setTimeout(function(){ 
      goto_next_page(); 
     }, 5000); 
    } 

    function goto_next_page(){ 
     page.evaluate(function() { 
      var a = document.querySelector('#block-system-main .next a'); 
      var e = document.createEvent('MouseEvents'); 
      e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      a.dispatchEvent(e); 
      waitforload = true; 

     }); 
     fetch_names(); 
    } 

    fetch_names(); 
}); 

你可以自己試試就明白了所有這些工作如何。

回答

3

你需要等待頁面點擊,而不是通過從fetch_namesgoto_next_page移動setTimeout()點擊之前加載後:

function fetch_names(){ 
    var name = page.evaluate(function() { 
     return [].map.call(document.querySelectorAll('div.pepitesteasermain h2 a'), function(name){ 
      return name.getAttribute('href'); 
     }); 
    }); 
    console.log(name.join('\n')); 
    page.render('1.png'); 
    goto_next_page(); 
} 

function goto_next_page(){ 
    page.evaluate(function() { 
     var a = document.querySelector('#block-system-main .next a'); 
     var e = document.createEvent('MouseEvents'); 
     e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); 
     a.dispatchEvent(e); 
     waitforload = true; 

    }); 
    window.setTimeout(function(){ 
     fetch_names(); 
    }, 5000); 
} 

注意,有更多的方式來等待比其他東西靜態超時。相反,你可以

+0

這工作,並感謝有關等待方式的新信息。 –