ActionChains.drag_and_drop(src, tgt).perform()ActionChains(driver).drag_and_drop(source, target).perform()# 快速参考 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()
操作步骤:
① 定位卡片 p7_card1/2/3 和目标区 p7_target;
② 循环调用 ActionChains(driver).drag_and_drop(card, target).perform();
③ 断言 p7_result 包含「全部 3 张」或目标区显示所有卡片。
💡 提示:前端卡片拖动需要自己实现 mousedown→mousemove→mouseup;Selenium 用 drag_and_drop(source, target) 一行搞定。
# 练习 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