Scroll Element into View with Selenium

SeleniumScrollAutomated Tests

Selenium Problem Overview


Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?

The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution is to scroll the item into view.

Selenium Solutions


Solution 1 - Selenium

Have tried many things with respect to scroll, but the below code has provided better results.

This will scroll until the element is in view:

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500); 

//do anything you want with the element

Solution 2 - Selenium

You can use the org.openqa.selenium.interactions.Actions class to move to an element.

Java:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

Python:

from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).move_to_element(driver.sl.find_element_by_id('my-id')).perform()

Solution 3 - Selenium

JavascriptExecutor js = (JavascriptExecutor) driver;
		js.executeScript("javascript:window.scrollBy(250,350)");

You may want to try this.

Solution 4 - Selenium

If you want to scroll on the Firefox window using the Selenium webdriver, one of the ways is to use JavaScript in the Java code. The JavaScript code to scroll down (to bottom of the web page) is as follows:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollTo(0, Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, document.documentElement.clientHeight));");

Solution 5 - Selenium

Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.

For example:

WebElement.sendKeys(Keys.DOWN);

Solution 6 - Selenium

In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:

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

In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.

I have a complete post and video on this:

http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/

Solution 7 - Selenium

webElement = driver.findElement(By.xpath("bla-bla-bla"));
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", webElement);

For more examples, go here. All in Russian, but Java code is cross-cultural :)

Solution 8 - Selenium

This worked for me:

IWebElement element = driver.FindElements(getApplicationObject(currentObjectName, currentObjectType, currentObjectUniqueId))[0];
 ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);

Solution 9 - Selenium

You can use this code snippet to scroll:

C#

var element = Driver.FindElement(By.Id("element-id"));
Actions actions = new Actions(Driver);
actions.MoveToElement(element).Perform();

There you have it

Solution 10 - Selenium

Use the driver to send keys like the pagedown or downarrow key to bring the element into view. I know it's too simple a solution and might not be applicable in all cases.

Solution 11 - Selenium

I found that the bounding rect of my element was not correct, leading to the browser scrolling well off the screen. However, the following code works rather well for me:

private void scrollToElement(WebElement webElement) throws Exception {
    ((JavascriptExecutor)webDriver).executeScript("arguments[0].scrollIntoViewIfNeeded()", webElement);
    Thread.sleep(500);
}

Solution 12 - Selenium

From my experience, Selenium Webdriver doesn't auto scroll to an element on click when there are more than one scrollable section on the page (which is quite common).

I am using Ruby, and for my AUT, I had to monkey patch the click method as follows;

class Element

      #
      # Alias the original click method to use later on
      #
      alias_method :base_click, :click

      # Override the base click method to scroll into view if the element is not visible
      # and then retry click
      #
      def click
        begin
          base_click
        rescue Selenium::WebDriver::Error::ElementNotVisibleError
          location_once_scrolled_into_view
          base_click
        end
      end

The 'location_once_scrolled_into_view' method is an existing method on WebElement class.

I apreciate you may not be using Ruby but it should give you some ideas.

Solution 13 - Selenium

The Ruby script for scrolling an element into view is as below.

$driver.execute_script("arguments[0].scrollIntoView(true);", element)
sleep(3)
element.click

Solution 14 - Selenium

This is a repeated solution with JavaScript, but with an added waiting for element.

Otherwise ElementNotVisibleException may appear if some action on the element is being done.

this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
WebDriverWait wait = new WebDriverWait(getDriver(), 5);
wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));

Solution 15 - Selenium

Selenium 2 tries to scroll to the element and then click on it. This is because Selenium 2 will not interact with an element unless it thinks that it is visible.

Scrolling to the element happens implicitly so you just need to find the item and then work with it.

Solution 16 - Selenium

Something that worked for me was to use the Browser.MoveMouseToElement method on an element at the bottom of the browser window. Miraculously it worked in Internet Explorer, Firefox, and Chrome.

I chose this over the JavaScript injection technique just because it felt less hacky.

Solution 17 - Selenium

I have used this way for scrolling the element and click:

List<WebElement> image = state.getDriver().findElements(By.xpath("//*[contains(@src,'image/plus_btn.jpg')]"));

for (WebElement clickimg : image)
{
  ((JavascriptExecutor) state.getDriver()).executeScript("arguments[0].scrollIntoView(false);", clickimg);
  clickimg.click();
}

Solution 18 - Selenium

def scrollToElement(element: WebElement) = {
  val location = element.getLocation
  driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
}

Solution 19 - Selenium

You may want to visit page Scroll Web elements and Web page- Selenium WebDriver using Javascript:

public static void main(String[] args) throws Exception {

    // TODO Auto-generated method stub
    FirefoxDriver ff = new FirefoxDriver();
    ff.get("http://toolsqa.com");
    Thread.sleep(5000);
    ff.executeScript("document.getElementById('text-8').scrollIntoView(true);");
}

Solution 20 - Selenium

If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.

When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\(ツ)

try
{
    element.Click();
}
catch {
    element.Click();
}

Solution 21 - Selenium

Sometimes I also faced the problem of scrolling with Selenium. So I used javaScriptExecuter to achieve this.

For scrolling down:

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

Or, also

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

For scrolling up:

js.executeScript("window.scrollBy(0,-250)", "");

Or,

js.executeScript("scroll(0, -250);");

Solution 22 - Selenium

In most of the situation for scrolling this code will work.

WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
js.executeScript("arguments[0].click();",element);

Solution 23 - Selenium

JAVA

Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".

Following import:

import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;

First you need get x y location the element.

//initialize element
WebElement element = driver.findElement(By.id("..."));
        
//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();
        
//scroll to x y 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");

Solution 24 - Selenium

I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.

The easiest solution would be

executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);

This scrolls the element into center of the page.

Solution 25 - Selenium

Javascript

The solustion is simple:

const element = await driver.findElement(...)
await driver.executeScript("arguments[0].scrollIntoView(true);", element)
await driver.sleep(500);

Solution 26 - Selenium

In Java we can scroll by using JavaScript, like in the following code:

driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");

You can assign a desired value to the "elm.scrollTop" variable.

Solution 27 - Selenium

Selenium can scroll to some element in the scrollbar automatically for some simple UI, but for lazy-load UI, scrollToElement is still needed.

This is my implementation in Java with JavascriptExecutor. You can find more details in Satix source code: http://www.binpress.com/app/satix-seleniumbased-automation-testing-in-xml/1958

public static void perform(WebDriver driver, String Element, String ElementBy, By by) throws Exception {
 try {
  //long start_time = System.currentTimeMillis();			
  StringBuilder js = new StringBuilder();
  String browser = "firefox";

  if (ElementBy.equals("id")) {
   js.append("var b = document.getElementById(\"" +
    Element + "\");");
  } else if (ElementBy.equals("xpath")) {
   if (!"IE".equals(browser)) {
    js.append("var b = document.evaluate(\"" +
     Element +
     "\", document, null, XPathResult.ANY_TYPE, null).iterateNext();");
   } else {
    throw new Exception("Action error: xpath is not supported in scrollToElement Action in IE");
   }
  } else if (ElementBy.equals("cssSelector")) {
   js.append("var b = document.querySelector(\"" +
    Element + "\");");
  } else {
   throw new Exception("Scroll Action error");
  }

  String getScrollHeightScript = js.toString() + "var o = new Array(); o.push(b.scrollHeight); return o;";

  js.append("b.scrollTop = b.scrollTop + b.clientHeight;");
  js.append("var tmp = b.scrollTop + b.clientHeight;");
  js.append("var o = new Array(); o.push(tmp); return o;");

  int tries = 1;
  String scrollTop = "0";
  while (tries > 0) {
   try {
    String scrollHeight = ((JavascriptExecutor) driver).executeScript(getScrollHeightScript).toString();
    if (scrollTop.equals(scrollHeight)) {
     break;
    } else if (driver.findElement(by).isDisplayed()) {
     break;
    }
    Object o = ((JavascriptExecutor) driver).executeScript(js.toString());
    scrollTop = o.toString();
    Thread.sleep(interval);
    tries++;
   } catch (Exception e) {
    throw new Exception("Action error:" +
     " javascript execute error : " + e.getMessage() + ", javascript : " + js.toString());
   }
  }

 } catch (Exception e) {
  try {
   ScreenshotCapturerUtil.saveScreenShot(driver, CLASSNAME);
  } catch (IOException e1) {
   throw new Exception("Save screenshot error!", e1);
  }
  throw e;
 }
}

Solution 28 - Selenium

I've been doing testing with ADF components and you have to have a separate command for scrolling if lazy loading is used. If the object is not loaded and you attempt to find it using Selenium, Selenium will throw an element-not-found exception.

Solution 29 - Selenium

This code is working for me:

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:window.scrollBy(250, 350)");

Solution 30 - Selenium

If nothing works, try this before clicking:

public void mouseHoverJScript(WebElement HoverElement) {

    String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
    ((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
}

Solution 31 - Selenium

The default behavior of Selenium us to scroll so the element is barely in view at the top of the viewport. Also, not all browsers have the exact same behavior. This is very dis-satisfying. If you record videos of your browser tests, like I do, what you want is for the element to scroll into view and be vertically centered.

Here is my solution for Java:

public List<String> getBoundedRectangleOfElement(WebElement we)
{
    JavascriptExecutor je = (JavascriptExecutor) driver;
    List<String> bounds = (ArrayList<String>) je.executeScript(
            "var rect = arguments[0].getBoundingClientRect();" +
                    "return [ '' + parseInt(rect.left), '' + parseInt(rect.top), '' + parseInt(rect.width), '' + parseInt(rect.height) ]", we);
    System.out.println("top: " + bounds.get(1));
    return bounds;
}

And then, to scroll, you call it like this:

public void scrollToElementAndCenterVertically(WebElement we)
{
    List<String> bounds = getBoundedRectangleOfElement(we);
    Long totalInnerPageHeight = getViewPortHeight(driver);
    JavascriptExecutor je = (JavascriptExecutor) driver;
    je.executeScript("window.scrollTo(0, " + (Integer.parseInt(bounds.get(1)) - (totalInnerPageHeight/2)) + ");");
    je.executeScript("arguments[0].style.outline = \"thick solid #0000FF\";", we);
}

Solution 32 - Selenium

A solution is:

public void javascriptclick(String element)
{
    WebElement webElement = driver.findElement(By.xpath(element));
    JavascriptExecutor js = (JavascriptExecutor) driver;

    js.executeScript("arguments[0].click();", webElement);
    System.out.println("javascriptclick" + " " + element);
}

Solution 33 - Selenium

If this object passing does not works:

await browser.executeScript( "arguments[0].scrollIntoView()", await browser.wait( until.elementLocated( By.xpath( "//div[@jscontroller='MC8mtf']" ) ), 1000 ) );

There is a demonstration for scroll to microphone button, on google page. Found it by javascript xpath, using chromedriver and selenium-webdriver.

start1() start a browser in narrow window, the microphone button does not shows.

start2() start a browser in narrow window, then scroll to microphone button.

require('chromedriver');
const { Builder, 
        By, 
        Key, 
        until
      }                = require('selenium-webdriver');

async function start1()  {

  var browser = new Builder()
                    .forBrowser( 'chrome' )
                    .build();
  await browser
        .manage()
        .window()
        .setRect( { width: 80, 
                    height: 1040, 
                    x:-10, 
                    y:0} 
                );
  await browser.navigate().to( "https://www.google.com/" );
}

async function start2()  {

  var browser = new Builder()
                    .forBrowser( 'chrome' )
                    .build();
  await browser
        .manage()
        .window()
        .setRect( { width: 80, 
                    height: 1040, 
                    x:-10, 
                    y:0} 
                );
  await browser.navigate().to( "https://www.google.com/" );
  await browser.executeScript( "document.evaluate(\"//div[@jscontroller='MC8mtf']\", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.scrollIntoView(true);");
}

start1();
start2();

Solution 34 - Selenium

For OpenQA.Selenium in C#:

WebDriver.ExecuteJavaScript("arguments[0].scrollIntoView({block: \"center\", inline: \"center\"});", Element);

Where WebDriver is new ChromeDriver(options) or similar.

Solution 35 - Selenium

Here is how I do it with PHP webDriver for Selenium. It Works for Selenium stand-alone server 2.39.0 + https://github.com/Element-34/php-webdriver + Firefox 25.0

$element=$session->welement("xpath", "//input[@value='my val']");
$element->click();
$element=$session->welement("xpath", "//input[@value='ma val2']");
$element->location_in_view(); // < -- this is the candy
$element->click();

Note: I use a customized version of the Element34 PHP-webdriver. But there is not any change in the core. I just use my "welement" instead of "element". But it makes no influence on the case in question. The driver author says "to allow almost all API calls to be a direct transformation of what is defined in the WebDriver protocol itself." So you should have no problem with other programming languages.

Just clicking will not work in my setup. It will do a scroll instead of click, so I had to click twice without calling "location_in_view()".

Note: This method works for elements that can be viewed, like an input of type button.

Take a look at: http://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location

The description for JsonWireProtocol# suggest usage of location + moveto, because location _in_view is an internal method.

Solution 36 - Selenium

Do a random click down the page:

driver.findElement(By.id("ID of a web element present below")).click

Then perform what you want to do.

Solution 37 - Selenium

I agree with everyone here, who say "Selenium has an implicit scroll option". Also if you were in Selenium 1 and now you have upgraded yourself to Selenium 2 and look for previous version's commands, you can use the command known as:

Seleniumbackeddriver.

WebDriver driver = new FirefoxDriver();
public void setUp() throws Exception {

    String baseUrl = "http://www.google.co.in/";
    selenium = new WebDriverBackedSelenium(driver, baseUrl);
}

You could make use of these and use commands of both versions.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDan at DemandView Question on Stackoverflow
Solution 1 - SeleniumAmithView Answer on Stackoverflow
Solution 2 - SeleniumsaschaView Answer on Stackoverflow
Solution 3 - SeleniumMayurView Answer on Stackoverflow
Solution 4 - SeleniumAnkit PandeyView Answer on Stackoverflow
Solution 5 - SeleniumDevDaveView Answer on Stackoverflow
Solution 6 - SeleniumMukesh otwaniView Answer on Stackoverflow
Solution 7 - SeleniumVovecUdalecView Answer on Stackoverflow
Solution 8 - Seleniumuser103View Answer on Stackoverflow
Solution 9 - SeleniumMohsin AwanView Answer on Stackoverflow
Solution 10 - SeleniumGanesh SView Answer on Stackoverflow
Solution 11 - SeleniumAshley FriezeView Answer on Stackoverflow
Solution 12 - SeleniumRobbie WarehamView Answer on Stackoverflow
Solution 13 - SeleniumSatheesh kumarView Answer on Stackoverflow
Solution 14 - SeleniumLukaszView Answer on Stackoverflow
Solution 15 - SeleniumAutomatedTesterView Answer on Stackoverflow
Solution 16 - SeleniumDavid PetersView Answer on Stackoverflow
Solution 17 - SeleniumBibekView Answer on Stackoverflow
Solution 18 - SeleniumomnomnomView Answer on Stackoverflow
Solution 19 - SeleniumvirusrocksView Answer on Stackoverflow
Solution 20 - SeleniumvicentedealencarView Answer on Stackoverflow
Solution 21 - SeleniumAnuraj RView Answer on Stackoverflow
Solution 22 - Seleniumsp324View Answer on Stackoverflow
Solution 23 - SeleniumfrianHView Answer on Stackoverflow
Solution 24 - SeleniumkiranjithView Answer on Stackoverflow
Solution 25 - SeleniumMasih JahangiriView Answer on Stackoverflow
Solution 26 - SeleniumHemantView Answer on Stackoverflow
Solution 27 - SeleniumEffieView Answer on Stackoverflow
Solution 28 - Seleniumuser3781490View Answer on Stackoverflow
Solution 29 - Seleniumvishal SinghView Answer on Stackoverflow
Solution 30 - SeleniumPrateekView Answer on Stackoverflow
Solution 31 - SeleniumdjangofanView Answer on Stackoverflow
Solution 32 - Seleniumakhilesh gulatiView Answer on Stackoverflow
Solution 33 - SeleniumSándor KrisztiánView Answer on Stackoverflow
Solution 34 - SeleniumIain BallardView Answer on Stackoverflow
Solution 35 - SeleniumKonstantin IvanovView Answer on Stackoverflow
Solution 36 - SeleniumAnkur GauravView Answer on Stackoverflow
Solution 37 - SeleniumSriharsha KaranthView Answer on Stackoverflow