Page scrolling plays a crucial role in automating web pages with varying content lengths. Selenium 1 (Selenium RC) and Selenium 2 (WebDriver) offer different approaches for page scrolling. Let's explore the equivalent methods for Selenium WebDriver:
In Selenium 1, the code for page scrolling was:
selenium.getEval("scrollBy(0, 250)");
To perform the same action in Selenium 2 (WebDriver), use the following code:
WebDriver driver = new FirefoxDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,250)");
Alternatively, you can use:
jse.executeScript("scroll(0, 250);");
For scrolling upward, simply negate the pixel value:
jse.executeScript("window.scrollBy(0,-250)");
To scroll to the bottom of the page, you have several options:
Using JavaScriptExecutor:
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Using Ctrl End Keys:
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL, Keys.END);
Using 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 do I implement page scrolling in Selenium WebDriver using Java?. For more information, please follow other related articles on the PHP Chinese website!