Scrolling to element using webdriver?
Solution 1:
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
Solution 2:
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
Solution 3:
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)
Solution 4:
Example:
driver.execute_script("arguments[0].scrollIntoView();", driver.find_element_by_css_selector(.your_css_selector))
This one always works for me for any type of selectors. There is also the Actions class, but for this case, it is not so reliable.