有没有方法使用Selenium和Python绑定实现鼠标悬停(hover)?
在这里阅读到的信息显示,之前有一个叫做 RenderedWebElement
的类,它里面有一个 hover
方法。不过,这个类只适用于Java,而且现在已经不再使用了。
在Python中,无法通过 action_chains
或者 WebElement
对象来实现 hover
操作。
有没有人知道在Python中怎么做这个?我在这里看过,但它使用了 RenderedWebElement
,所以对我帮助不大。
我使用的是:Python 2.7,Windows Vista,Selenium 2,Python绑定
编辑:有一个 selenium.selenium.selenium
对象的方法叫 mouse_over
,但我不知道怎么在没有先启动独立服务器的情况下创建这个对象。
编辑 请查看被标记为答案的回复的评论,以防你和我一样有误解!
2 个回答
8
@AutomatedTester 给大家提供了一个很棒的解决方案!
下面是我怎么使用这个方案的。
我使用信号来正确地退出 PhantomJS,因为它有时候会在当前进程中卡住。
我更喜欢使用 find_element_by_xpath
,因为在 Chrome 浏览器中很容易找到 xpath。
具体操作如下:
右键点击 -> 检查 -> 右键点击 -> 复制 -> 复制Xpath
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()
134
要实现鼠标悬停的效果,你需要使用 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()