有没有办法使用Selenium和Python绑定执行鼠标悬停(悬停在元素上)?

Ash*_*win 44 python selenium python-bindings selenium-webdriver

在这里阅读,显然曾经是一个带有悬停方法的RenderedWebElement类.但是,它专门用于Java(在这里搜索python绑定文档无济于事),因此已被弃用于Java.

无法使用action_chains(方法列表)执行悬停,也不能使用webelement(方法列表)对象执行悬停.

有关如何为python执行此操作的任何想法?在这里,但它使用RenderedWebElement,因此没有太多帮助.

Python 2.7,Windows Vista,Selenium 2,Python绑定

编辑:对于selenium.selenium.selenium对象有一个方法"mouse_over",但我无法想象一种方法来创建一个实例,而不必运行独立服务器.

问题已经回答:如果您有误解,请仔细阅读标记为答案的回复评论!

Aut*_*ter 80

要进行悬停,您需要使用该move_to_element方法.

这是一个例子

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains

firefox = webdriver.Firefox()
firefox.get('http://foo.bar')
element_to_hover_over = firefox.find_element_by_id("baz")

hover = ActionChains(firefox).move_to_element(element_to_hover_over)
hover.perform()
Run Code Online (Sandbox Code Playgroud)

  • 添加到我大约一年前的评论中,这似乎在 Mac 上得到解决。我正在使用 2.26 python 绑定并且不再出现“无法执行本机交互”错误 (2认同)

hyu*_*lee 6

@AutomatedTester 为社区提供了一个很好的解决方案!

下面是我如何使用它。

我使用信号正确退出PhantomJS,因为它有时会挂在当前进程中。

我更喜欢使用,find_element_by_xpath因为在 chrome 中可以很容易地找到 xpath。

就是这样:

右键单击 -> 检查 -> 右键单击​​ -> 复制 -> CopyXpath

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import signal

browser = webdriver.PhantomJS()
browser.implicitly_wait(3)

def hover(browser, xpath):
    element_to_hover_over = browser.find_element_by_xpath(xpath)
    hover = ActionChains(browser).move_to_element(element_to_hover_over)
    hover.perform()



browser.service.process.send_signal(signal.SIGTERM)  # kill the specific phantomjs child proc
browser.quit()
Run Code Online (Sandbox Code Playgroud)