Home  >  Article  >  Java  >  How to Scroll Pages in Selenium 2 with WebDriver (Java)?

How to Scroll Pages in Selenium 2 with WebDriver (Java)?

Susan Sarandon
Susan SarandonOriginal
2024-11-10 02:02:02996browse

How to Scroll Pages in Selenium 2 with WebDriver (Java)?

Page Scrolling in Selenium 2 with WebDriver (Java)

In Selenium 1, page scrolling was achieved using the selenium.getEval("scrollBy(0, 250)") method. In Selenium 2, the equivalent code is as follows:

Scrolling Down or Up

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;

// Scroll down
jse.executeScript("window.scrollBy(0,250)");
// OR
jse.executeScript("scroll(0, 250);");

// Scroll up
jse.executeScript("window.scrollBy(0,-250)");
// OR
jse.executeScript("scroll(0, -250);");

Scrolling to the Bottom of the Page

Using JavaScriptExecutor:

jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Using Keys.CONTROL Keys.END:

driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);

Using the Java Robot Class:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_END);
robot.keyRelease(KeyEvent.VK_CONTROL);

The above is the detailed content of How to Scroll Pages in Selenium 2 with WebDriver (Java)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn