Selenium is a tool that developers can use to automate the testing of web apps. With this tool, it’s possible to write test scripts that perform several actions. For example, you can use Selenium to load a webpage, click on links and buttons, or even type text into an input field.
Another important action Selenium supports is scrolling a webpage. Usually, the amount of content on web pages exceeds the browser window size. As a result, users need to scroll in one direction or the other to view more content.
In the following sections of this post, we provide an easy practical guide for scrolling in Selenium. So, keep reading to learn more.
Prerequisites
To follow along better, make sure to have the following:
- Selenium installed
- Selenium WebDriver plugin for your preferred programming language
Expand Your Test Coverage
How to Scroll to an Element in Selenium
Now let’s dive into detailed steps for scrolling in Selenium.
Tip: For this example, we use JavaScript. Hence, you must have Node.js installed. Also, install the WebDriver JavaScript library in your project directory using the following commands:
npm install selenium-webdriver
and
npm init -y
Step 1: Prepare the Webpage to Test
Not all pages are scrollable. For example, a page with a small bit of text that reads “Hello world” will not scroll because the content is so brief that it doesn’t require scrolling. Hence, make sure you test a page with enough content to require scrolling to view more content.
You can load any actual webpage with scrollable content to test scrolling. Or, for the sake of this tutorial, you can create an HTML file with the following code and test scrolling on this example web page:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> <title>Birds of same forest</title> </head> <body> <div class="container mt-4"> <div class="row"> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>P</h1> <p>Parrot</p> </div> </div> </div> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>C</h1> <p>Crow</p> </div> </div> </div> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>P</h1> <p>Peacock</p> </div> </div> </div> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>P</h1> <p>Pigeon</p> </div> </div> </div> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>G</h1> <p>Goose</p> </div> </div> </div> <div class="col-md-4 mb-4"> <div class="card"> <div class="card-body"> <h1>D</h1> <p>Dove</p> </div> </div> </div> </div> <p>Keep scrolling...</p> <div style="height: 100vh;"></div> <p class="footer">© 2022</p> </div> </body> </html>
Step 2: Load Page Using WebDriver
Now that we have a page to test scrolling on let’s load the page using Selenium WebDriver. To do that, create a new JavaScript file and add the following code. Then save the file as test.js:
const {Builder, By, Key, until} = require('selenium-webdriver'); (async ()=> { let driver = await new Builder().forBrowser('chrome').build(); const url = 'file:///Users/ea/Development/tutorial-examples/selenium-scroll/index.html'; await driver.get(url); })();
The above code creates a new instance of WebDriver using the Builder() method. The default browser for the WebDriver instance is set to Chrome via the forBrowser() method. You can select another browser as the default by changing the value in the method’s argument.
Tip: Remember to change the value for URL to the actual path for the webpage you want to test.
Step 3: Locate the Target Element
The target element here is whichever element you wish to scroll to. For the sake of this tutorial, let’s use the footer of our example page as the target element.
Open the test.js file from the last step and look for this line:
await driver.get(url);
Just after that line, add the following code on a new line:
let element = driver.findElement(By.className('footer'));
The above code enables Selenium to locate the target element by its class property.
Step 4: Scroll to Target Element
At this point, we have successfully written code that can load our example webpage and locate the element we wish to scroll to. Now, we’ll look at how to scroll to the element. To achieve this, we’ll use WebDriver’s executeScript() method.
The executeScript Method
This method is inside the webdriver.js file from the WebDriver JavaScript library. It allows us to run custom JavaScript code inside Selenium. In the second parameter, you can use a string parameter to supply the JavaScript code you want to execute and specify other arguments, like the target element. The syntax for this method is as follows:
driver.executeScript("javascript code", arguments);
For our example, add the following code to test.js after the last line from the previous step:
driver.executeScript("arguments[0].scrollIntoView(true);", element);
This code executes JavaScript scrollIntoView, which causes our browser to scroll to the view specified. The second parameter of executeScript() is the element we wish to scroll to, and arguments[0] refers to the first element in a list of parameters. For our example, we only have one element (our target element), and the 0th index refers to it.
Step 5: Run the Test
Now that we have everything in place, we can test our code by running the following command in the terminal:
node test.js
If everything runs well, you should get the following result in a web browser:
Horizontal Scroll
The example we’ve considered scrolls from the top to locate an element at the bottom of a web page. This type of scroll is vertical. Let’s consider another case where we require horizontal scrolling, from right to left.
Add the following code to your index.html file, on a new line, just after the opening <body> tag.
<div class="scrollmenu"> <a href="#home">How to select elements in selenium</a> <a href="#news">Introduction to Selenium</a> <a href="#contact">Selenium javascript exams</a> <a href="#about">Selenium official documentation for Javascript</a> <a href="#contact">Everything selenium news</a> <a href="#about">Another selenium example link title</a> <a href="#about" class="last">A lil even longer 3</a> </div>
Notice that the last link has its class property set to last. This is the element we’ll scroll to.
To finish up the page design for this example, add the following code inside the <head> section:
<style> div.scrollmenu { background-color: #333; overflow: auto; white-space: nowrap; } div.scrollmenu a { display: inline-block; color: white; text-align: center; padding: 14px; text-decoration: none; } div.scrollmenu a:hover { background-color: #777; } </style>
The above CSS will make extra content in scrollmenu scrollable to the right.
The final step for this example is adding the code that tells Selenium to scroll to the element with class last. Open test.js and add the following code, just below the previous line:
let elementH = driver.findElement(By.className('last')); driver.executeScript("arguments[0].scrollIntoView(true);", elementH);
Run test.js again, as you did in step 5. Observe that Selenium automatically scrolls to the target link element.
Here’s the complete code test.js:
const {Builder, By, Key, until} = require('selenium-webdriver'); (async ()=> { let driver = await new Builder().forBrowser('chrome').build(); const url = 'file:///Users/ea/Development/tutorial-examples/selenium-scroll/index.html'; await driver.get(url); let element = driver.findElement(By.className('footer')); driver.executeScript("arguments[0].scrollIntoView(true);", element); let elementH = driver.findElement(By.className('last')); driver.executeScript("arguments[0].scrollIntoView(true);", elementH); })();
Summing Up
First, we mentioned that Selenium is a tool for browser automation and it can perform many actions, including scrolling a webpage.
Then, we walked through two examples of how to scroll to a specific element using Selenium and JavaScript. The first example scrolled from the top to locate an element on the bottom of a webpage. This type of scrolling is vertical. The second example demonstrated how to code a horizontal scroll.
For our examples, we used the JavaScript programming language to write the code that controls Selenium. However, you can achieve the same goal using any programming language supported by Selenium.
Although Selenium is a helpful tool, the initial setup process can be complex. In addition, you may run into issues when you write code for Selenium, and as a result, you end up doing extra debugging. Testim is a great alternative for Selenium that requires less work to author and maintain tests. You can try Testim for free here.
What to read next
How to Take a Screenshot in Selenium: A Walkthrough With Code