Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

I have written the following code in Selenium 1 (a.k.a Selenium RC) for page scrolling using java:

selenium.getEval("scrollBy(0, 250)"); 

What is the equivalent code in Selenium 2 (WebDriver)?

like image 267
Ripon Al Wasim Avatar asked Sep 06 '12 04:09

Ripon Al Wasim


People also ask

How do I scroll up and scroll down in Selenium?

Hence, to scroll up or down with Selenium, a JavaScriptExecutor is a must. The scrollBy() method involves two parameters, x, and y, that represent the horizontal and vertical pixel values, respectively.

How do you scroll down vertically in Selenium?

Selenium can execute JavaScript commands with the help of the executeScript method. To scroll down vertically in a page we have to use the JavaScript command window. scrollBy. Then pass the pixel values to be traversed along the x and y axis for horizontal and vertical scroll respectively.

How does Selenium handle scrollbar in Java?

Code for handling Scroll bar using an in-built scroll option. In the above program code, scrolling is handled in Selenium using Actions class. This is done by creating an object of Actions class by passing the driver.

How do you check scroll position using Selenium?

To check the position we shall use the Javascript executor. We have to verify the value of the window. pageYOffset in the browser. While the URL is launched, the scroll is at the top the value of window.


1 Answers

Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll down some pixel and scroll up

For Scroll down:

WebDriver driver = new FirefoxDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("window.scrollBy(0,250)"); 

OR, you can do as follows:

jse.executeScript("scroll(0, 250);"); 

For Scroll up:

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

Scroll to the bottom of the page:

Scenario/Test steps:
1. Open a browser and navigate to TestURL
2. Scroll to the bottom of the page

Way 1: By using JavaScriptExecutor

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

Way 2: By pressing ctrl+end

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

Way 3: By 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); 
like image 159
Ripon Al Wasim Avatar answered Oct 08 '22 14:10

Ripon Al Wasim