Python Selenium如何实现更真实的鼠标移动模拟以规避网站安全检测?
模拟浏览器内人类鼠标移动行为的实现方案
该需求完全可以实现,目前主流的实现方案都不会操控系统级物理光标,所有模拟操作仅作用于目标浏览器实例内部。
方案1:使用Selenium原生Actions类实现
这是最简便的实现方式,Selenium的Actions接口本身就是用于模拟复杂用户交互,所有事件仅在浏览器上下文生效,不影响系统光标。
你可以在点击目标元素前,先模拟随机范围的鼠标移动、悬停等行为,示例代码如下:
from selenium.webdriver.common.action_chains import ActionChains import random import time # 初始化动作链 actions = ActionChains(driver) # 先模拟随机移动:随机选页面上多个位置移动,加入随机偏移和延迟 for _ in range(random.randint(3, 8)): # 生成随机坐标,范围可以根据页面尺寸自定义 random_x = random.randint(100, 1000) random_y = random.randint(100, 800) actions.move_by_offset(random_x, random_y) # 加随机停顿,模拟人类移动间隙 actions.pause(random.uniform(0.05, 0.2)) # 重置偏移,避免坐标累加 actions.move_by_offset(-random_x, -random_y) # 移动到目标按钮,加入随机偏移,不要刚好对准元素中心 target = driver.find_element(By.XPATH, button) actions.move_to_element_with_offset(target, random.randint(-5, 5), random.randint(-5, 5)) # 点击前随机悬停100-300ms actions.pause(random.uniform(0.1, 0.3)) # 执行点击 actions.click() # 执行所有动作 actions.perform()
注意:不要使用固定的移动路径、固定延迟,匀速直线移动非常容易被反爬策略识别,加入随机参数后模拟真实度会大幅提升。
方案2:使用Chrome DevTools Protocol(CDP)注入底层鼠标事件
如果原生Actions类仍然被网站检测,可以调用CDP的Input接口直接向页面注入鼠标事件,该方案模拟层级更低,被检测概率更小,同样不影响系统物理光标,示例代码如下:
import random import time def simulate_mouse_move(driver, x, y): driver.execute_cdp_cmd("Input.dispatchMouseEvent", { "type": "mouseMoved", "x": x, "y": y, "button": "none" }) def simulate_mouse_click(driver, x, y): # 先模拟鼠标按下 driver.execute_cdp_cmd("Input.dispatchMouseEvent", { "type": "mousePressed", "x": x, "y": y, "button": "left", "clickCount": 1 }) # 按下到抬起的随机间隔,模拟人类点击延迟 time.sleep(random.uniform(0.05, 0.15)) # 模拟鼠标抬起 driver.execute_cdp_cmd("Input.dispatchMouseEvent", { "type": "mouseReleased", "x": x, "y": y, "button": "left", "clickCount": 1 }) # 先执行随机范围的鼠标移动 for _ in range(random.randint(3, 8)): rx = random.randint(100, 1000) ry = random.randint(100, 800) simulate_mouse_move(driver, rx, ry) time.sleep(random.uniform(0.05, 0.2)) # 获取目标元素的坐标后点击 target_rect = driver.find_element(By.XPATH, button).rect target_x = target_rect['x'] + target_rect['width']/2 + random.randint(-5, 5) target_y = target_rect['y'] + target_rect['height']/2 + random.randint(-5, 5) simulate_mouse_move(driver, target_x, target_y) time.sleep(random.uniform(0.1, 0.3)) simulate_mouse_click(driver, target_x, target_y)
核心优化要点
- 鼠标移动不要走直线,可在路径中加入±5到±10像素的随机偏移
- 移动速度不要匀速,接近目标元素时适当降低移动速度
- 点击前加入100-300ms的随机悬停时间
- 可随机模拟少量误移动:比如先移到目标旁的无关区域,再移回目标位置
内容的提问来源于stack exchange,提问作者codex21
相关产品推荐
相关产品推荐

