Finding position of viewport in Selenium Python?

Viewed 453

I need to find the position of the top left corner of the viewport in Selenium. I know we can use drive_get_window_position() to get the window position, but I need just the position of the part that renders. Is that possible?

The use case is that I am attempting to use Selenium to get the coordinates of an element, and need to move the cursor to it. Since Selenium only moves the virtual mouse and not the visible cursor, I am using pyautogui to move the cursor to absolute coordinates.

However because the browser position affects where the absolute coordinates should be, I need to know where the viewport is so I can offset appropriately. Using the get_window_position() works for x coordinates but not y coordinates due to the various menus and toolbars.

1 Answers

location_once_scrolled_into_view¶

THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover where on the screen an element is so that we can click it. This method should cause the element to be scrolled into view.

https://www.selenium.dev/selenium/docs/api/py/webdriver_remote/selenium.webdriver.remote.webelement.html#module-selenium.webdriver.remote.webelement

Returns the top lefthand corner location on the screen, or None if the element is not visible.

Eg:

e = driver.find_element_by_xpath('//html')
print(e.location_once_scrolled_into_view)
Related