Selenium ActionChains: 创建对象并模拟鼠标缓慢移动
如何使用 Selenium ActionChains 模拟鼠标缓慢移动
Selenium 的 ActionChains 对象可以用来模拟各种鼠标和键盘操作,例如点击、移动、拖放等。本文将介绍如何使用 ActionChains 对象创建鼠标移动操作,并通过move_by_offset 和 pause 方法实现鼠标缓慢移动的效果。
创建 ActionChains 对象
# 创建 ActionChains 对象
actions = ActionChains(driver)
el = driver.find_element(by=By.CSS_SELECTOR, value='#remoteVideo')
actions.move_to_element_with_offset(el, xoffset1-(el.size['width']/2) +1, yoffset1-(el.size['height']/2)+1).perform()
actions.click_and_hold().perform()
# 计算每一步的移动距离
step_x = (xoffset2 - xoffset1) / 10
step_y = (yoffset2 - yoffset1) / 10
# 慢慢移动鼠标
for i in range(10):
actions.move_by_offset(step_x, step_y).perform()
actions.pause(0.5) # 暂停0.5秒,可以调整时间间隔
actions.release().perform()
logger.debug(f'slide_point:{xoffset1, yoffset1, xoffset2, yoffset2}')
代码说明
- 创建 ActionChains 对象:
actions = ActionChains(driver) - 定位元素:
el = driver.find_element(by=By.CSS_SELECTOR, value='#remoteVideo') - 将鼠标移动到元素中心:
actions.move_to_element_with_offset(el, xoffset1-(el.size['width']/2) +1, yoffset1-(el.size['height']/2)+1).perform() - 按住鼠标左键:
actions.click_and_hold().perform() - 计算每一步的移动距离:
step_x = (xoffset2 - xoffset1) / 10和step_y = (yoffset2 - yoffset1) / 10 - 使用循环移动鼠标:
for i in range(10): - 使用
move_by_offset方法移动鼠标:actions.move_by_offset(step_x, step_y).perform() - 使用
pause方法暂停一段时间:actions.pause(0.5) - 释放鼠标左键:
actions.release().perform()
总结
本文介绍了如何使用 Selenium 的 ActionChains 对象创建鼠标移动操作,并通过move_by_offset 和 pause 方法实现鼠标缓慢移动的效果。该方法可以用来模拟用户在网页上的真实操作,例如在交互式图表上绘制图形、或进行其他需要精细操作的任务。
原文地址: https://www.cveoy.top/t/topic/qEk9 著作权归作者所有。请勿转载和采集!