0

I'm trying to find the correct location of an element in selenium but this is givin me some troubles, this is my code


from selenium import webdriver
from pynput.mouse import Button, Controller as MouseController
mouse = MouseController()

driver = webdriver.Chrome()

driver.maximize_window()
driver.set_page_load_timeout(30)

driver.get("https://stackoverflow.com/")
element = driver.find_element_by_xpath('//*[@id="mainbar"]/div[1]/h1')
x, y = element.location["x"], element.location["y"]

mouse.position = x, y

But i don't understand why it returns a position different from the correct element location

Mat.C
  • 1,379
  • 2
  • 21
  • 43
  • What are you trying to accomplish? What are your expected element locations? – orde Apr 16 '19 at 16:12
  • The element location that i was expecting was a corner of the writing 'Top Questions' at the link – Mat.C Apr 16 '19 at 16:17
  • 1
    Maybe `x, y = element.location["x"]+element.size["width"]/2, element.location["y"]+element.size["height"]/2` ? – lojza Apr 17 '19 at 14:09

1 Answers1

0

Pynput is going to the absolute coordinates based off of the screen size whereas the coordinates you get from selenium are relative to the browser window.

In order to counteract this you need to take the browser navigation bar size into account when calculating the y coordinate:

browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
x, y = element.location["x"], element.location["y"] + browser_navigation_panel_height

This post pointed me to a solution.

NB: This solution will only work when the browser window is maximised

cullzie
  • 2,705
  • 2
  • 16
  • 21