Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll up the page to the top in selenium

How to scroll the webpage to the top of the page.

I know scrolling the page to the bottom is:

window.scrollTo(0,document.body.scrollHeight)

just like that is it possible to scroll the page to the top

like image 642
Pala Bhaskar Avatar asked Apr 15 '16 12:04

Pala Bhaskar


People also ask

How do I scrollTo the top of the web using Selenium?

Javascript method ScrollBy() scrolls the web page to the specific number of pixels. The syntax of ScrollBy() methods is : executeScript("window. scrollBy(x-pixels,y-pixels)");

How do I scroll up page in Selenium?

Hence, to scroll up or down with Selenium, a JavaScriptExecutor is a must. The scrollBy() method involves two parameters, x, and y, that represent the horizontal and vertical pixel values, respectively.

How do you get to the top of the page in Selenium Python?

To scroll up to the top of a webpage using Selenium, you can use the execute_script() function to execute the JavaScript function window. scrollTo() and pass '0' for the second parameter.

How do you scroll down to the bottom of a page in Selenium Java?

Selenium runs the commands in Javascript with the execute_script() method. For scrolling down to the bottom of the page, we have to pass (0, document. body. scrollHeight) as parameters to the method scrollBy().


2 Answers

To scroll to the top of the page, just scroll to the 0, 0:

window.scrollTo(0, 0);

Or, as an alternative option, you can scroll into view of the header element (or some other element on top):

WebElement element = driver.findElement(By.tagName("header"));

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].scrollIntoView();", element); 
like image 123
alecxe Avatar answered Sep 19 '22 16:09

alecxe


Use action class, as some UI frameworks don't work well with JavaScript scrollTO

actions.sendKeys(keys.Home).build().perform();
actions.sendKeys(keys.END).build().perform();
like image 37
Frozen Avatar answered Sep 18 '22 16:09

Frozen