Python Selenium for循环重复点击同一坐标偏移问题如何解决
问题原因
ActionChains的move_by_offset()方法偏移量默认相对于当前鼠标的实时位置计算:第一次点击完成后鼠标会停留在目标坐标处,第二次循环时会基于这个停留位置继续叠加偏移量,自然就会出现坐标累加的问题,Selenium本身不会在操作完成后自动把鼠标重置回视口原点。
可行解决方法
方法1:点击后主动反向偏移归位
每次执行完点击操作后,主动给当前鼠标位置添加反向偏移,手动重置到初始基准点,适合不需要频繁修改坐标的场景:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By # 旧版find_element_by_*方法已废弃,需导入By driver = webdriver.Chrome() driver.get('https://www.google.co.in/') actions = ActionChains(driver) # 可在循环外实例化一次复用,不需要每次循环新建 X = 550 Y = 331 for i in range(5): driver.find_element(By.XPATH, "//input[@name='q']").send_keys("hey") # 移动到目标坐标点击 actions.move_by_offset(X,Y).click().perform() # 反向偏移回到初始基准点,消除本次偏移影响 actions.move_by_offset(-X, -Y).perform()
方法2:锚定页面根元素计算绝对偏移(更推荐)
直接将偏移基准锚定到页面根元素<html>的左上角(也就是视口原点(0,0)),每次偏移都基于固定原点计算,不需要手动处理鼠标重置,稳定性更高:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By driver = webdriver.Chrome() driver.get('https://www.google.co.in/') actions = ActionChains(driver) # 锚定页面根元素作为偏移基准 root = driver.find_element(By.TAG_NAME, "html") X = 550 Y = 331 for i in range(5): driver.find_element(By.XPATH, "//input[@name='q']").send_keys("hey") # 直接基于视口原点计算坐标,不会累加偏移 actions.move_to_element_with_offset(root, X, Y).click().perform()
额外提示
如果你需要点击的坐标是屏幕全局坐标而非页面视口坐标,可以直接用pyautogui库实现点击,它的坐标默认是全局绝对坐标,不会出现偏移累加问题,写法为pyautogui.click(x=550, y=331)。
内容的提问来源于stack exchange,提问作者sizo_abe
相关产品推荐
相关产品推荐

