2015-04-17 17 views
2

我試圖滾動頁面完全使用此代碼:滾動一個Ajax網頁完全使用硒的webdriver

JavascriptExecutor js = (JavascriptExecutor) Browser; 
js.executeScript("javascript:window.onload=toBottom();"+ 
              "function toBottom(){" +"window.scrollTo(0,Math.max(document.documentElement.scrollHeight," +"document.body.scrollHeight,document.documentElement.clientHeight));" +"}"); 
js.executeScript("window.status = 'fail';"); 

//Attach the Ajax call back method 
js.executeScript("$(document).ajaxComplete(function() {" + "status = 'success';});"); 
js.executeScript("window.status = 'fail';"); 

//Attach the Ajax call back method 
js.executeScript("$(document).ajaxComplete(function() {" +"status = 'success';});"); 

此代碼工作正常,並滾動頁面的第一次嘗試,但是當頁面滾動下來,新數據出現在頁面上,並且此代碼無法再次滾動。 所以我需要的是有人會幫我滾動頁面直到結束,直到滾動完成。

我爲此使用任何循環嗎?

幫助/建議/反應將不勝感激!

+0

頁面的例子? – stanjer

+0

例如,您可以考慮twitter或linkedin主頁,例如當您向下滾動顯示更多推文時。 –

+0

但該頁面上沒有「結束」 – stanjer

回答

0

所以,我會做這樣的事情:

bool pageEnded = false; 
while (!pageEnded) { 
    JavascriptExecutor js = (JavascriptExecutor) Browser; 
    js.executeScript("window.scrollTo(0, document.body.offsetHeight);"); 
    pageEnded = (String)js.executeScript("return document.readyState;") ? true; 
} 
+0

謝謝。我會嘗試並讓你知道。 –

+0

Stanjer它不工作.. –

+0

它不是完全滾動或什麼?請告訴我你是怎麼做的?你在做什麼?這也可能是你的頁面正在使用一些js框架並做一些意想不到的事情。 – stanjer

1

我有類似功能的頁面,另一個問題我以前回答。我不熟悉任何通用的方法來知道頁面是否沒有任何其他元素加載。在我的情況下,該頁面設計爲在每個滾動中加載40/80(忘記確切數量)元素。因爲,大多數情況下,我知道滾動的估計數量(因爲我正在使用測試公司,並且我知道在db中有多少元素),所以我可以估計滾動的數量並執行以下操作以處理該頁面。

public void ScrollPage(int counter) 
{ 
    const string script = 
     @"window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));"; 


    int count = 0; 

    while (count != counter) 
    { 
     IJavaScriptExecutor js = _driver as IJavaScriptExecutor; 
     js.ExecuteScript(script); 

     Thread.Sleep(500); 

     count++; 
    } 
} 

看我其他的答案here

的Java代碼等效

public void ScrollPage(int counter) throws InterruptedException { 

     String script = "window.scrollTo(0,Math.max(document.documentElement.scrollHeight,document.body.scrollHeight,document.documentElement.clientHeight));"; 
     int count = 0; 

     while (count != counter) 
     { 
      ((JavascriptExecutor)driver).executeScript(script); 

      Thread.sleep(500); 
      count++; 
     } 
    } 

使用

ScrollPage(10); 

需要滾動的地方

+0

嗨Saifur, 我試過你的java等效代碼,但它不工作。 –

+0

你能提供更多信息什麼不起作用嗎?什麼是例外? – Saifur

+0

Hi Saifur, 它只向下滾動頁面。就例外而言,沒有這種例外。 我試過用它的方法滾動頁面。它只向下滾動頁面一次。 –

相關問題