Selenium scroll to element-Scroll Element into View with Selenium

781    Asked by naveen_1186 in Devops , Asked on Jul 18, 2021

 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 selenium scroll to element?

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, the easiest solution, scroll the item into view.

Answered by Rachel Kerr

I suggest you to use the org.openqa.selenium.interactions.Actions library which with the help of actions class and the driver object will 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()I hope this helps!



Your Answer

Interviews

Parent Categories