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

16

88

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)?

Fumigator answered 6/9, 2012 at 4:51 Comment(0)
F
145

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);
Fumigator answered 6/9, 2012 at 4:59 Comment(7)
The above code is for scroll down. For scroll up: jse.executeScript("scroll(250, 0)"); Only the value would be reverseFumigator
No - that will scroll to the right. Scroll up will be scroll(0,-250)Sera
Thanks Stephen. Both scroll(250,0) and scroll(0,-250) should work for scroll up.Fumigator
For scroll up (0, -250) is logical. I do agree with Stephen.Fumigator
jse.executeScript("window.scrollBy(0,250)", ""); it works fine. I want to use variable as int y = 250; jse.executeScript("window.scrollBy(0,y)", ""); An error shows in this case as "y is not defined". How to use variable in this case?Fumigator
@RiponAlWasim Did you ever find a solution for that issue?Draco
@RiponAlWasim you would just concatenate the variable into your string in whatever way you like, e.g. jse.executeScript("window.scrollBy(0," + y + ")", "")Delude
D
44

Scrolling to the bottom of a page:

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Desdamonna answered 20/6, 2015 at 17:33 Comment(3)
just to mention, it is for scroll downDemesne
it is not working in my salesforce application, where as window.scrollBy(0,250) works. But it does not scroll to the end of the page.Epizootic
@AshokkumarGanesan did you try window.scrollBy(0,document.body.scrollHeight)?Aggarwal
T
16

There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.

Below is the code which always works for me if I want to scroll up or down

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

You can get full code from here Scroll Page in Selenium

If you want to scroll for a element then below piece of code will work for you.

je.executeScript("arguments[0].scrollIntoView(true);",element);

You will get the full doc here Scroll for specific Element

Tristatristam answered 10/6, 2015 at 20:15 Comment(2)
This worked if I have to scroll down. How can I scroll up the page?Fertility
The first snippet of code only scrolls the page, not the element itself, how can I do that?Harmful
M
13

This may not be an exact answer to your question (in terms of WebDriver), but I've found that the java.awt library is more stable than selenium.Keys. So, a page down action using the former will be:

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);
Morley answered 4/6, 2015 at 17:26 Comment(0)
D
5
JavascriptExecutor js = ((JavascriptExecutor) driver);

Scroll down:

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

Scroll up:

js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");
Downstage answered 28/7, 2017 at 9:1 Comment(0)
Z
2

Try this:

Actions dragger = new Actions(driver);
WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[@id='jobreslist_outercontainer']/div/div[2]/div"));

// drag downwards
int numberOfPixelsToDragTheScrollbarDown = 50;
for (int i = 10; i < 500; i += numberOfPixelsToDragTheScrollbarDown) {
    try {
        // this causes a gradual drag of the scroll bar, 10 units at a time
        dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
        Thread.sleep(1000L);
    } catch(Exception e1) {}
}

// now drag opposite way (downwards)
numberOfPixelsToDragTheScrollbarDown = -50;
for (int i = 500; i > 10; i += numberOfPixelsToDragTheScrollbarDown) {
    // this causes a gradual drag of the scroll bar, -10 units at a time
    dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0, numberOfPixelsToDragTheScrollbarDown).release().perform();
    Thread.sleep(1000L);
}
        
Zig answered 27/6, 2013 at 2:23 Comment(1)
I actually like this since it scrolls how a user wouldBuddle
D
2

Javascript

We can scroll to a specific element:

const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);
Deitz answered 14/7, 2021 at 5:10 Comment(0)
R
1

You should add a scroll to the page to select all elements using:

Selenium.executeScript("window.scrollBy(0,450)", "");

If you have a large list, add the scroll several times through the execution. Note the scroll only go to a certain point in the page for example (0, 450).

Roadability answered 24/8, 2016 at 16:39 Comment(0)
B
1

I did not want to use JavaScript, or any external libraries, so this was my solution (C#):

IWebElement body = Driver.FindElement(By.TagName("body"));

IAction scrollDown = new Actions(Driver)
    .MoveToElement(body, body.Size.Width - 10, 15) // position mouse over scrollbar
    .ClickAndHold()
    .MoveByOffset(0, 50) // scroll down
    .Release()
    .Build();

scrollDown.Perform();

You can also easily make this an extension method for scrolling up or down on any element.

Buddle answered 19/1, 2017 at 18:24 Comment(2)
@raffamaiden put heads on your browser lol... I'm not sure why anyone would want to test against a browser that their users aren't actually going to use anywaysBuddle
You are right. But the OP did not specify it was testing an app. You can use Selenium also for other purposes (e.g. webscraping).Jesus
S
1

1.To scroll page to the bottom use window.scrollTo(0,document.body.scrollHeight) as parameter

//Code to navigate to bottom

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollHeight));

2.To scroll page to the top use window.scrollTo(0,document.body.scrollTop) as parameter

//Code to navigate to top

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollTop));

3.To scroll page to the Left use window.scrollTo(0,document.body.scrollLeft) as parameter

//Code to navigate to left

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,document.body.scrollLeft));

4.To scroll to certain point window.scrollTo(0,500) as parameter

//Code to navigate to certain point e.g. 500 is passed as value here

WebDriver driver = new ChromeDriver();
JavascriptExecutor jsExecuter = (JavascriptExecutor)driver;
jsExecuter.executeScript(window.scrollTo(0,500));

To check the navigation directly in browser , open developers tool in browser and navigate to console. Execute the command on console window.scrollTo(0,400) enter image description here

Shlomo answered 8/3, 2020 at 6:42 Comment(0)
D
0
JavascriptExecutor jse = ((JavascriptExecutor) driver);
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

This code works for me. As the page which I'm testing, loads as we scroll down.

Dikmen answered 3/11, 2016 at 9:11 Comment(0)
P
0

Javascript executor always does the job perfectly:

((JavascriptExecutor) driver).executeScript("scroll(0,300)");

where (0,300) are the horizontal and vertical distances respectively. Put your distances as per your requirements.

If you a perfectionist and like to get the exact distance you like to scroll up to on the first attempt, use this tool, MeasureIt. It's a brilliant firefox add-on.

Podium answered 10/11, 2016 at 12:29 Comment(0)
S
0

Thanks for Ripon Al Wasim's answer. I did some improvement. because of network problems, I retry three times until break loop.

driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollBy(0,2000)")

    # Wait to load page
    time.sleep(scroll_delay)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")

    if last_height == new_height:
        try_times += 1

    if try_times > 3:
        try_times = 0
        break
    last_height = new_height
Steamheated answered 6/3, 2018 at 10:55 Comment(0)
B
0

JavascriptExecutor is best to scroll down a web page window.scrollTo Function in JavascriptExecutor can do this

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0,100"); 

Above code will scroll down by 100 y coordinates

Bacteriophage answered 11/8, 2020 at 12:34 Comment(0)
S
0
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");
Shipment answered 14/9, 2020 at 0:18 Comment(0)
S
-2
  1. If you want to scroll the page vertically to perform some action, you can do it using the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

        Where ‘JavascriptExecutor’ is an interface, which helps executing JavaScript through Selenium WebDriver. You can use the following code to import.
    

import org.openqa.selenium.JavascriptExecutor;

2.If you want to scroll at a particular element, you need to use the following JavaScript.

WebElement element = driver.findElement(By.xpath(“//input [@id=’email’]”));((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, element);

Where ‘element’ is the locator where you want to scroll.

3.If you want to scroll at a particular coordinate, use the following JavaScript.
((JavascriptExecutor)driver).executeScript(“window.scrollBy(200,300)”); Where ‘200,300’ are the coordinates.

4.If you want to scroll up in a vertical direction, you can use the following JavaScript. ((JavascriptExecutor) driver).executeScript(“window.scrollTo(document.body.scrollHeight,0)”);

  1. If you want to scroll horizontally in the right direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(2000,0)”);

  2. If you want to scroll horizontally in the left direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(-2000,0)”);

Skolnik answered 5/10, 2018 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.