【问题标题】:Is there a way to perform a mouseover (hover over an element) using Selenium and Python bindings?有没有办法使用 Selenium 和 Python 绑定执行鼠标悬停(悬停在元素上)?
【发布时间】:2012-01-05 08:34:14
【问题描述】:

阅读here,显然曾经有一个带有hover 方法的RenderedWebElement 类。然而,它是专门为 Java 制作的(我已经搜索了 Python 绑定文档但无济于事),并且后来被 Java 弃用了。

hover 不能使用 action_chainsWebElement 对象执行。

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

我正在使用:Python 2.7、Windows Vista、Selenium 2、Python 绑定

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

编辑请仔细阅读标记为答案的回复,以防万一您像我一样有误解!

【问题讨论】:

    标签: python selenium selenium-webdriver python-bindings


    【解决方案1】:

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

    【讨论】:

    • 最后一行应该是“hover.perform()” 是的,我已经尝试过了,但是当我说悬停时,我有这样的想法,当我将鼠标悬停在一个元素上时,它会向我显示文本应该显示(例如,如果您将鼠标悬停在“标记”元素上,就在此评论上方,您会看到“标记此帖子以解决严重问题或版主注意”弹出窗口(我不知道该怎么称呼它))有什么想法吗?跨度>
    • 与悬停无关,所应用的 CSS 可以,但您所追求的是元素的标题。为此,您需要在 WebElement 上使用 get_attribute('title')
    • 我认为这是获得它的方法....我猜错了....感谢您提供正确的方法!
    • 知道mac什么时候支持这个功能吗?我收到“无法执行本机交互”错误
    • 添加到我将近一年前的评论中,这似乎在 Mac 上得到了解决。我正在使用 2.26 python 绑定,不再出现“无法执行本机交互”错误
    【解决方案2】:

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

    以下是我的使用方法。

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

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

    方法如下:

    右键->检查->右键->复制->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()
    

    【讨论】:

      猜你喜欢
      • 2021-07-15
      • 2011-11-08
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 2013-02-27
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多