The Issue

While automating there will be times when you have to scroll to a particular point on a page in order to locate an element and perform any desired operations exactly on that element of the webpage. There will be scenarios that would need the cursor to be scrolled to a particular location to perform user-defined operations and other cases where the element is only visible if we scroll down to the desired location in a large scrollable webpage.

Scrolling to an exact location plays a vital role in capturing screenshots at the time of error/failure when the webpage has a long scrollable content

The Answer

There are multiple ways to make the element visible by scrolling to its location. In order to implement the scroll operation, Selenium leverages JavaScriptExecutor.

The Code

Here’s a look at the scroll functions which we could use –

  1. Scrolling to a location by pixel coordinates
  2. Scrolling by the visibility of an element
  3. Scrolling to the top/bottom of the page
  4. Scrolling horizontally on a page

Scrolling to a location by pixel coordinates:

Let us understand this syntax with an example

 In this example, we used wait (e.g. sleep 5) to have enough time to notice the page scrolling to the desired location and capture a screenshot (e.g. @driver.save_screenshot “3qihomepage.png”) at that location

Scrolling by the visibility of an element:

An example illustrating the above syntax:

Scrolling to the top/bottom of the page:

Above syntax is explained by the following example:

Scrolling horizontally on the page:

Above syntax is explained by the following example:

The Result

When the above code is saved as a ruby (.rb) file, it performs the following actions:

  • Opens the browser
  • Navigates to “3Qi Labs website”
  • According to your requirement, the page scrolls to the desired location
  • Takes screenshot to make sure it is navigated to the desired view

The Takeaway

Though Selenium does not offer scrolling operations, an interface called JavaScriptExecutor can be used to perform the required actions. You can scroll to any point on the webpage no matter how long the page is. These suggestions enable the user to better understand operations that can be performed on long webpages which is the crux of any modern website