鼠标操作练习 · 拖拽

拖拽 drag_and_drop — ActionChains.drag_and_drop() 一步完成拖放

练习 · 拖拽 drag_and_drop()

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

练习 7 · 拖拽 drag_and_drop()

📋 练习要求 · 拖拽 drag_and_drop()
概念拖放是按住源元素后移动到目标位置再释放,Selenium 提供了一步式 API
Selenium APIActionChains(driver).drag_and_drop(source, target).perform()
练习要点
  • drag_and_drop 是 click_and_hold + move_to_element + release 的封装
  • 适用于简单直线拖拽,复杂路径用分步组合
  • 拖拽对目标元素位置敏感,确保目标在可视区域内
# 快速参考
from selenium.webdriver.common.action_chains import ActionChains
card  = driver.find_element(By.ID, "p7_card1")
tgt   = driver.find_element(By.ID, "p7_target")
ActionChains(driver).drag_and_drop(card, tgt).perform()
📋 本节练习清单
  • ✅ 练习目标:将 3 张卡片依次拖到目标区,断言全部接收
7 练习目标:拖拽卡片到目标区,验证拖放结果

操作步骤:
① 定位卡片 p7_card1/2/3 和目标区 p7_target;
② 循环调用 ActionChains(driver).drag_and_drop(card, target).perform();
③ 断言 p7_result 包含「全部 3 张」或目标区显示所有卡片。

拖拽交互演示区(真实拖动)
👆 按住卡片拖到右侧目标区,每张都可以独立拖入
📦 源区
卡片 A
卡片 B
卡片 C
🎯 目标区
等待拖入
等待拖放操作...
💬 操作日志(拖放实时记录)
// 按住任意卡片开始拖动...

💡 提示:前端卡片拖动需要自己实现 mousedown→mousemove→mouseup;Selenium 用 drag_and_drop(source, target) 一行搞定。

查看参考答案(Python Selenium)
# 练习 7 参考答案 · 拖拽
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

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

card_ids = ["p7_card1", "p7_card2", "p7_card3"]
for cid in card_ids:
    card = driver.find_element(By.ID, cid)
    actions.drag_and_drop(card, target).perform()
    time.sleep(0.3)

# 断言
assert "3" in driver.find_element(By.ID, "p7_result").text

关于我们

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. 如涉及版权问题或内容建议,请及时通过联系方式与我们沟通,我们将第一时间处理。