ActionChains.move_to_element(element).perform()move_to_element_with_offset 微调ActionChains(driver).move_to_element(el).perform()# 快速参考 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()
操作步骤:
① 用 driver.find_element(By.ID, "p4_trigger") 定位「悬停我」按钮;
② 调用 ActionChains(driver).move_to_element(trigger).perform() 悬停;
③ 断言 p4_submenu 子菜单元素可见。
💡 提示:move_to_element() 对应 DOM 的 mouseenter,常用于触发 CSS :hover 菜单或 tooltip,离开后 mouseleave 会关闭子菜单。
# 练习 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()