Scrolling to element using webdriver?
You are trying to run Java code with Python. In Python/Selenium, the org.openqa.selenium.interactions.Actions
are reflected in ActionChains
class:
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element_by_id("my-id")
actions = ActionChains(driver)
actions.move_to_element(element).perform()
Or, you can also "scroll into view" via scrollIntoView()
:
driver.execute_script("arguments[0].scrollIntoView();", element)
If you are interested in the differences:
- scrollIntoView vs moveToElement
In addition to move_to_element()
and scrollIntoView()
I wanted to pose the following code which attempts to center the element in the view:
desired_y = (element.size['height'] / 2) + element.location['y']
window_h = driver.execute_script('return window.innerHeight')
window_y = driver.execute_script('return window.pageYOffset')
current_y = (window_h / 2) + window_y
scroll_y_by = desired_y - current_y
driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by)
It's not a direct answer on question (its not about Actions
), but it also allow you to scroll easily to required element:
element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view
This actually intend to return you coordinates (x
, y
) of element on page, but also scroll down right to target element