Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Selenium - click on element purely based on its location based on body element offset

I have a question that was somehow discussed here ([python][selenium] on-screen position of element) but that doesn't currently do what I'm trying to achieve.

My goal is the following: element.location gives the position of the top left corner of element in the browswer. I have a website in which, even if it's probably not a good selenium practice, I want to be able to click on such element purely based on its position because it has never changed and likely never will. Assuming element.location gives {'x': 253, 'y': 584}, this is the code I tried so far with no luck

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver.maximize_window()
url = "https://learn.letskodeit.com/p/practice"
driver.get(url)
open_window_elem = driver.find_element_by_id("openwindow")

# from wherever the mouse is, I move to the top left corner of the broswer
action = ActionChains(driver)
action.move_by_offset(-1000, -1000)    
action.click()
action.perform()

y_coordinate = open_window_elem.location["y"]
x_coordinate = open_window_elem.location["x"]

action = ActionChains(driver)
action.move_by_offset(x_coordinate, y_coordinate)
action.click()
action.perform()

Nothing happens when I run this code. I would except to open a new window. Can somebody help?

like image 662
Angelo Avatar asked Aug 10 '26 15:08

Angelo


1 Answers

It is better to click in the middle of the element than in its corner. Sometimes corners are not clickable. Coordinates x and y of "openwindow" element these are the coordinates of its upper left corner.

I suggest calculating the coordinates of the element's center. To do this, first check the width and height of the element:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
driver.maximize_window()
url = "https://learn.letskodeit.com/p/practice"
driver.get(url)

open_window_elem = "//button[@id='openwindow']"

x = int(driver.find_element_by_xpath(open_window_elem).location['x'])
y = int(driver.find_element_by_xpath(open_window_elem).location['y'])
width = int(driver.find_element_by_xpath(open_window_elem).size['width'])
height = int(driver.find_element_by_xpath(open_window_elem).size['height'])

action = webdriver.common.action_chains.ActionChains(driver)
action.move_by_offset(x + width/2, y + height/2)
action.click()
action.perform()
like image 93
drazewski Avatar answered Aug 13 '26 05:08

drazewski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!