简体   繁体   中英

Selenium webdriver - End of the page(using vertical scroll)

How can I check if I reached the end of the page (using vertical scroll)?

From the Webdriver - press the page down key till end of the page. Using for loop I have done this :

for(int di=0; di<40; di++) { 
   driver.findElement(By.tagName("body")).sendKeys(Keys.PAGE_DOWN);
   Thread.sleep(1500);
}

My for loop always executed 40 times even its less size. So I need help how I can check if it reached the end of the page, because if I reached then I will break and come out of the loop.

I think First you have to pick an element which exist at the end of page. Lets say there is one footer label with id company-email

boolean flag = true;
while(flag){
if(driver.findElements(By.id("company-email").size()>0){

    flag = false;
}
else{

   driver.findElement(By.tagName("body")).sendKeys(Keys.PAGE_DOWN);
   Thread.sleep(1500);
   }
}

You can use this to scroll till end of a page :

public static void scrollToEndOfPage(WebDriver driver) {
        ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight)");
    }

and after it has been executed you can perform further operations.

If you want to scroll to a particular WebElement you can use below method :

 public static void scrollToElement(WebDriver driver, WebElement element) {
            ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", element);
        }

Hope that helps you.

Thanks for the support, Finally got a idea and implemented its met my expectations

First measure the scroll height

 JavascriptExecutor executor = (JavascriptExecutor) driver;
            long value = (Long) executor.executeScript("return document.body.scrollHeight");

and looping

for (int f = 500; f <= value; f += 500) {
            JavascriptExecutor jsc = (JavascriptExecutor) driver;
            jsc.executeScript("window.scrollTo(0," + f + ")");
            Thread.sleep(1500);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM