简体   繁体   English

如何使用硒Webdriver根据元素的坐标单击元素

[英]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. 因此,我们正在开发的Web应用程序具有TV / PC模式,并且我正在测试在这两种模式之间进行转换的能力。 ` `

 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. 问题是,当我从PC切换到电视时,屏幕“放大”,使按钮出现在没有缩放的位置。 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. 因此,我无法使用“ tv_to_pc”方法单击按钮,“原因是单击实际按钮时,它将单击按钮应位于的位置。

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 . 我建议您使用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. 有关更多信息,请参见如何在Python网络驱动程序中执行javascript和其他问题。 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. 另外...您不想使用这样的XPath。 Any XPath that starts at the HTML tag or is more than just a few levels deep is going to be very brittle. 任何始于HTML标记或深度超过几个级别的XPath都将非常脆弱。 Do some googling on selenium xpaths and read some guides for more info. 在selenium xpaths上进行一些谷歌搜索,并阅读一些指南以获取更多信息。

try moveToElement and then perform click 尝试moveToElement然后执行单击

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

x is xoffset y is yoffset x是xoffset y是yoffset

Please see that if you use Javascript for click its not going to be native click. 请注意,如果您使用Javascript进行点击,则它不会是原生点击。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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