0

i want to know the position of an element relative to the canvas element.

i initially create a point at x and y values being -50 and -50 like below using selenium webdriver

canvas = driver.find_element_by_xpath("//div[@class='canvas_holder']")
ActionChains(driver).move_to_element(canvas).move_by_offset(-50, -50).click().perform()

The above creates a point. now i have to check if the point is created at -50 and -50 how can i do it.

could anyone provide me some ideas. thanks.

enter image description here

someuser2491
  • 1,848
  • 5
  • 27
  • 63

1 Answers1

0

I found it on Selenium: get coordinates or dimensions of element with Python - Stack Overflow

Got it! The clue was on selenium.webdriver.remote.webelement — Selenium 3.14 documentation.

WebElements have the properties .size and .location. Both are of type dict.

driver = webdriver.Firefox()

e = driver.find_element_by_xpath("//someXpath")

location = e.location
size = e.size

print(location)
print(size)

Output:

{'y': 202, 'x': 165}
{'width': 77, 'height': 22}

They also have a property called rect which is itself a dict, and contains the element's size and location.

Then subtract the position of the element you want from its parent position. For example, if d1 is the parentElement.location, and d2 is the childElement.location,

then, python - How to subtract values from dictionaries - Stack Overflow

I think a very Pythonic way would be using dict comprehension:

d3 = {key: d1[key] - d2.get(key, 0) for key in d1.keys()}

Note that this only works in Python 2.7+ or 3.

  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/199901/discussion-on-answer-by-angular-orbit-how-to-get-the-position-of-an-element-rela). – Samuel Liew Sep 24 '19 at 11:21