【发布时间】:2013-05-24 07:43:44
【问题描述】:
使用 Python 版本的 Selenium,是否可以单击 DOM 中的某个元素并指定要单击的坐标?
Java 版本有 clickAt 方法,它实际上完全符合我的要求,但在 Python 中找不到等价物。
【问题讨论】:
使用 Python 版本的 Selenium,是否可以单击 DOM 中的某个元素并指定要单击的坐标?
Java 版本有 clickAt 方法,它实际上完全符合我的要求,但在 Python 中找不到等价物。
【问题讨论】:
应该这样做!即您需要使用来自 webdriver 的动作链。一旦你有了一个实例,你只需注册一堆动作,然后调用perform() 来执行它们。
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.google.com")
el=driver.find_elements_by_xpath("//button[contains(string(), 'Lucky')]")[0]
action = webdriver.common.action_chains.ActionChains(driver)
action.move_to_element_with_offset(el, 5, 5)
action.click()
action.perform()
这将使鼠标从按钮的左上角向下移动 5 像素,向右移动 5 像素我感到很幸运。然后它会click()。
请注意,您必须使用perform()。否则什么都不会发生。
【讨论】:
您感到困惑的原因是clickAt 是一种旧的 v1 (Selenium RC) 方法。
WebDriver 的概念略有不同,'Actions'。
具体来说,Python 绑定的“Actions”构建器实时here。
clickAt 命令的思想是点击特定元素相对的特定位置。
同样可以在 WebDriver 中实现,使用“操作”构建器。
希望updated documentation 可以提供帮助。
【讨论】:
您可以使用 Edge 浏览器在 python 中的动作链执行任务:
from selenium.webdriver import ActionChains
actionChains = ActionChains(driver)
button_xpath = '//xapth...'
button = driver.find_element_by_xpath(button_xpath)
actionChains.move_to_element(button).click().perform()
但有时 Action 链找不到 DOM 元素。因此,以下列方式使用执行 scipt 的更好选择:
button_xpath = '//xapth...'
button = driver.find_element_by_xpath(button_xpath)
driver.execute_script("arguments[0].click();", button)
【讨论】:
我没有亲自使用过这种方法,但是通过查看selenium.py 的源代码,我发现了以下方法,它们看起来就像你想要的那样 - 他们看起来包装了clickAt:
def click_at(self,locator,coordString):
"""
Clicks on a link, button, checkbox or radio button. If the click action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("clickAt", [locator,coordString,])
def double_click_at(self,locator,coordString):
"""
Doubleclicks on a link, button, checkbox or radio button. If the action
causes a new page to load (like a link usually does), call
waitForPageToLoad.
'locator' is an element locator
'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse event relative to the element returned by the locator.
"""
self.do_command("doubleClickAt", [locator,coordString,])
它们出现在 selenium 对象中,这里是它们的online API documentation。
【讨论】: