How to scroll down or up a page in selenium?

In this article, we will cover how to scroll down or up a page in selenium.

I need to validate the element, which is not visible on the screen, if I use a scrollbar, I can be able to view that element on my page.

How can I automate to scroll the page to view the element I am looking for?

In Selenium, there is a JavaScriptExecutor interface that executes JavaScript methods via Selenium Webdriver.

Here is the syntax for the JavaScriptExecutor,

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

ScrollIntoView moves the scroll bar to the top whereas boolean condition false moves it to the bottom.

scroll down or up a page in selenium

We can also scroll using pixel

Here is the syntax for that,

executeScript("window.scrollBy(x-pixels,y-pixels)");
How to scroll down or up a page in selenium

Suppose in the case of scrolling down to the bottom of the page,

js.executeScript("window.scrollTo(0, document.body.scrollHeight)");
How to scroll down or up a page in selenium
Conclusion

In this article, we have covered how to scroll up or down a page in selenium using Javascript. We hope that the content is useful.

Leave a Reply