演示 Selenium 的 两种鼠标移动方式:移动到元素中心 和 移动到绝对坐标。悬停菜单、hover 效果触发、拖拽定位等场景都需要它。
两种 API 区别:
move_to_element(el) → 移动到 元素中心,自动考虑视口滚动位置move_by_offset(x, y) → 移动到 当前鼠标的相对偏移,注意是相对于当前鼠标,不是相对于页面左上角move_to_element_with_offset(el, dx, dy) → 移动到元素的某个偏移点,精确控制点击位置💡 悬停菜单实战:ActionChains(driver).move_to_element(menu).perform() → 等子菜单出现 → click 子菜单项。ActionChains 会自动排队执行,不用分散调用。
move_to_element 以元素中心为锚点;
move_to_element_with_offset 以元素左上角为原点偏移;
move_by_offset 以当前鼠标位置为原点;
move_to_point 以浏览器视口左上角为绝对坐标原点(Selenium 4.6+)。from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.action_chains import ActionChains # 1. 启动浏览器 + 打开演示页面 driver = webdriver.Chrome() driver.get("https://autotest-505.pages.dev/mouse_op_tech_sections/mouse_move_tech.html") actions = ActionChains(driver) # ── ① move_to_element:移动到元素中心 ── menu = driver.find_element(By.ID, "menuFile") actions.move_to_element(menu).perform() # ── ② move_to_element_with_offset:元素内偏移 ── # 元素左上角为原点,向右 +50px、向上 -30px canvas = driver.find_element(By.ID, "offsetCanvas") actions.move_to_element_with_offset(canvas, xoffset=50, yoffset=-30).perform() # ── ③ move_by_offset:相对当前位置移动 ── # 鼠标当前位置为原点,向右 +30、向下 +25 actions.move_by_offset(dx=30, dy=25).perform() # 常见:按住 → 相对移动 → 释放(拖拽 = 分步式) ball = driver.find_element(By.ID, "ball") actions.click_and_hold(ball) \ .move_by_offset(30, 25) \ .release() \ .perform() # ── ④ move_to_point:视口绝对坐标(Selenium 4.6+) ── # 浏览器视口左上角为原点 actions.move_to_point(x=400, y=300).perform() # ── 方法对比速查 ── # move_to_element(el) 锚点: 元素中心 常用度: ★★★★★ # move_to_element_with_offset 锚点: 元素左上角 常用度: ★★★☆☆ # move_by_offset 锚点: 当前鼠标位置 常用度: ★★★★☆(拖拽必备) # move_to_point 锚点: 视口左上角 常用度: ★★☆☆☆(4.6+) # 3. 关闭浏览器 driver.quit()