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

问题描述 投票:39回答:2

阅读here,显然曾经是一个RenderedWebElement类与hover方法。但是,它专门用于Java(我搜索过Python绑定文档无济于事),因此已经不再使用Java了。

使用hover也不能使用action_chains对象执行WebElement

有关如何为Python执行此操作的任何想法?我一直是here但它使用RenderedWebElement,因此没有太多帮助。

我正在使用:Python 2.7,Windows Vista,Selenium 2,Python Bindings

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

编辑请仔细阅读标记为答案的回复评论,以防万一你有误解,就像我做的那样!

python selenium selenium-webdriver python-bindings
2个回答
71
投票

要进行悬停,您需要使用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()

2
投票

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

以下是我如何使用它。

我使用signal来正确退出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()
© www.soinside.com 2019 - 2024. All rights reserved.