鼠标操作练习 · 移动

移动 move_to_element — ActionChains.move_to_element() 悬停触发 hover 效果

练习 · 移动 move_to_element()

左击 右击 双击 移动 按住 释放 拖拽 滚动

练习 4 · 移动 move_to_element()

📋 练习要求 · 移动 move_to_element()
概念悬停(hover / mouseover)通过将鼠标移到元素上触发子菜单或提示框
Selenium APIActionChains(driver).move_to_element(el).perform()
练习要点
  • move_to_element 将鼠标移动到元素中心并悬停
  • 常用于多级菜单、Tooltip 提示、下拉菜单展开
  • 某些框架悬停后菜单会自动消失,后续 click 要快
# 快速参考
from selenium.webdriver.common.action_chains import ActionChains
trigger = driver.find_element(By.ID, "p4_trigger")
ActionChains(driver).move_to_element(trigger).perform()
submenu = driver.find_element(By.ID, "p4_submenu")
assert submenu.is_displayed()
📋 本节练习清单
  • ✅ 练习目标:定位触发按钮 → move_to_element → 断言子菜单可见
4 练习目标:悬停触发子菜单,验证菜单显示

操作步骤:
① 用 driver.find_element(By.ID, "p4_trigger") 定位「悬停我」按钮;
② 调用 ActionChains(driver).move_to_element(trigger).perform() 悬停;
③ 断言 p4_submenu 子菜单元素可见。

悬停交互演示区
等待悬停操作...
子菜单状态:隐藏 已悬停 0 次
💬 操作日志(悬停实时记录)
// 请将鼠标移到左侧按钮上

💡 提示:move_to_element() 对应 DOM 的 mouseenter,常用于触发 CSS :hover 菜单或 tooltip,离开后 mouseleave 会关闭子菜单。

查看参考答案(Python Selenium)
# 练习 4 参考答案 · 移动
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains

driver.get("https://autotest-505.pages.dev/mouse_op_practice.html")
trigger = driver.find_element(By.ID, "p4_trigger")
actions = ActionChains(driver)

# 把鼠标移到元素上(悬停)
actions.move_to_element(trigger).perform()

# 断言子菜单可见
submenu = driver.find_element(By.ID, "p4_submenu")
assert submenu.is_displayed()

关于我们

Python 自动化测试学习平台是一个面向软件测试工程师、开发人员及在校学生的交互式在线学习平台,专注于 Selenium WebDriver 与 Python unittest 自动化测试技能的教学与实践。

我们以"理论 + 实战 + 可交互演示"为核心特色,将八种常规元素定位和Javascript定位、元素操作、自动化测试工具、单元测试、测试模型等知识体系拆分为模块化课程,每个模块都配有可点击、可输入、可运行的模拟练习页面。

平台致力于降低自动化测试的入门门槛,让学习者从"看懂代码"到"动手实操",逐步掌握企业级自动化测试框架的设计与落地能力。

联系方式

📧邮箱:lq@selenium-auto-test.com

📞电话:0755-12345678

📍地址:深圳

💬微信公众号:Selenium自动化测试

🐙GitHub:github.com/selenium-auto-test

免责声明

1. 本平台所有示例代码、演示页面及教程内容均仅供学习交流使用,不构成任何商业推广或技术服务承诺。

2. 平台中的 Selenium API 描述、Python 语法说明均以官方文档为准,如有版本差异请以对应官方文档为准。

3. 学习者在实际项目中应用平台所学内容时,应结合自身项目环境进行充分测试,本平台不对因直接使用示例代码而产生的任何直接或间接损失承担责任。

4. 本平台所引用的第三方库(Selenium、ChromeDriver、unittest 等)版权归其各自作者及维护者所有。

5. 如涉及版权问题或内容建议,请及时通过联系方式与我们沟通,我们将第一时间处理。