简体   繁体   中英

How to click on an element based on its coordinates with selenium webdriver

So, the web app we're developing has a TV/PC mode, and i'm testing the ability to transit between these two modes. `

 def pc_to_tv(self):
        pc_to_tv = self.driver.find_element_by_xpath(
            'html/body/div[1]/div/topbar/header/div[2]/div[2]/div[1]/button[1]')
        pc_to_tv.click()

 def tv_to_pc(self):
      tv_to_pc = self.driver.find_element_by_xpath(
            'html/body/div[1]/div/topbar/header/div[2]/div[2]/div[1]/button[2]')
      tv_to_pc.click()`

The problem is, when i switch from pc to tv, the screen "zooms in", making the button appear in the same place it would be without the zoom. so, i can't click on the button with my 'tv_to_pc' method, 'cause instead on clicking on the actual button, it clicks where the button should be.

So, the solution i found was clicking on the button with coordinates, that way i'll actually click on the place i want, instead of clicking on an unclickable place like i was doing.

The thing is, i don't know how to do this, and need help on this matter.

I would suggest that you just click the button using JavaScriptExecutor . It will click it no matter where it is on the page. See How to execute a javascript in a Python webdriver and other questions for more info. The general format is

element = driver.find_element_by_id("someId") 
driver.execute_script("arguments[0].click();", element)

Also... you don't want to use XPaths like that. Any XPath that starts at the HTML tag or is more than just a few levels deep is going to be very brittle. Do some googling on selenium xpaths and read some guides for more info.

try moveToElement and then perform click

((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
new Actions(driver).moveToElement(element, x, y).click().perform();

x is xoffset y is yoffset

Please see that if you use Javascript for click its not going to be native click.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM