Selenium 鼠标绝对坐标移动及还原:示例代码和最佳实践
在 Selenium 中,可以使用 ActionChains 类来模拟鼠标操作。要将鼠标移动到绝对坐标上,可以使用 move_by_offset 方法,指定相对于当前位置的偏移量来移动鼠标。然后,使用 move_to_element 方法将鼠标移动到绝对坐标上。\n\n以下是一个示例代码,展示了如何将鼠标移动到绝对坐标上,并在每次移动后都将鼠标还原回初始位置 (0, 0)。\n\npython\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\n\n# 创建 WebDriver 实例\ndriver = webdriver.Chrome()\n\n# 打开网页\ndriver.get("http://example.com")\n\n# 创建 ActionChains 实例\nactions = ActionChains(driver)\n\n# 获取初始位置\ninitial_position = driver.get_window_position()\n\n# 将鼠标移动到绝对坐标 (100, 100)\nactions.move_by_offset(100, 100).perform()\n\n# 将鼠标移动到绝对坐标 (200, 200)\nactions.move_by_offset(100, 100).perform()\n\n# 将鼠标移动回初始位置 (0, 0)\nactions.move_to_element_with_offset(driver.find_element_by_tag_name("html"), initial_position["x"], initial_position["y"]).perform()\n\n# 关闭浏览器\ndriver.quit()\n\n\n在上述示例代码中,我们使用 get_window_position 方法获取了初始位置,并在每次移动后使用 move_to_element_with_offset 方法将鼠标移动回初始位置。
原文地址: https://www.cveoy.top/t/topic/qBbZ 著作权归作者所有。请勿转载和采集!