You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在pytest框架中使用Python Selenium ActionChains实现鼠标悬停自动化

pytest 框架下使用 Selenium ActionChains 实现鼠标悬停的示例

前置依赖

首先安装所需第三方包:

pip install pytest selenium webdriver-manager

实现说明

Selenium 中的 ActionChains 类是实现复杂鼠标交互的核心工具,鼠标悬停对应 move_to_element() 方法,所有动作链定义完成后必须调用 perform() 才会实际执行操作。
pytest 中可以将浏览器驱动的初始化、销毁逻辑封装为 fixture,减少用例冗余代码。

完整可运行代码

import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 浏览器驱动fixture,每个测试用例执行前初始化驱动,执行后自动关闭
@pytest.fixture(scope="function")
def driver():
    chrome_service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=chrome_service)
    driver.maximize_window()
    driver.implicitly_wait(10)
    yield driver
    # 用例执行结束后销毁驱动
    driver.quit()

def test_mouse_hover_operation(driver):
    # 示例场景:百度首页悬停右上角「更多」按钮
    driver.get("https://www.baidu.com")

    # 定位需要悬停的目标元素
    target_element = driver.find_element(By.LINK_TEXT, "更多")

    # 执行鼠标悬停操作
    ActionChains(driver).move_to_element(target_element).perform()

    # 验证悬停效果:判断展开的菜单是否可见
    hover_menu = driver.find_element(By.CLASS_NAME, "s-top-more-content")
    assert hover_menu.is_displayed(), "鼠标悬停操作未生效,对应菜单未展示"

注意事项

  • 若目标元素位于 iframe 内部,需要先使用 driver.switch_to.frame() 切入对应 iframe 后再执行元素定位和悬停操作
  • 交互元素加载存在延迟的场景,建议使用显式等待替代隐式等待,提升用例稳定性
  • 悬停后需要操作子元素的场景,可以直接在动作链中追加后续操作,示例如下:
    # 悬停后点击子菜单元素
    sub_menu = driver.find_element(By.LINK_TEXT, "文库")
    ActionChains(driver).move_to_element(target_element).click(sub_menu).perform()
    

内容的提问来源于stack exchange,提问作者ashish labh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:54:03