You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义补间函数实现PyAutoGUI鼠标移动随机化?

实现PyAutoGUI随机化鼠标移动的自定义方案

PyAutoGUI内置的补间函数仅控制移动的速度缓动曲线,不会改变直线路径。要模拟人类的随机鼠标移动,需要在移动过程中给中间点添加随机偏移,或让X/Y轴的进度缓动逻辑分离。以下是两种实用的实现方案:

方案1:带随机偏移的类人移动函数

这个方法生成一系列带随机偏移的中间路径点,同时保留缓动曲线的速度变化,更贴近人类操作习惯(接近目标时偏移更小、更精准):

import pyautogui
import random
import math

def human_like_move_to(target_x, target_y, duration=2, tween=pyautogui.easeInOutQuad, num_points=20):
    # 获取当前鼠标起始位置
    start_x, start_y = pyautogui.position()
    # 计算起点到终点的直线距离
    total_distance = math.hypot(target_x - start_x, target_y - start_y)
    
    # 生成带偏移的路径点列表
    path_points = []
    for i in range(num_points + 1):
        # 计算当前移动进度(0=起点,1=终点)
        t = i / num_points
        # 应用缓动曲线调整进度,实现自然的速度变化
        eased_t = tween(t)
        
        # 计算直线上的基础位置
        base_x = start_x + (target_x - start_x) * eased_t
        base_y = start_y + (target_y - start_y) * eased_t
        
        # 根据剩余距离计算最大偏移量(越接近终点,偏移越小)
        remaining_dist = total_distance * (1 - eased_t)
        max_offset = min(remaining_dist * 0.15, 30)  # 限制最大偏移不超过30像素
        # 生成随机偏移
        offset_x = random.uniform(-max_offset, max_offset)
        offset_y = random.uniform(-max_offset, max_offset)
        
        # 添加偏移后的路径点
        path_points.append((base_x + offset_x, base_y + offset_y))
    
    # 依次移动到每个路径点,分配时间
    step_duration = duration / num_points
    for x, y in path_points[1:]:  # 跳过起始点
        pyautogui.moveTo(x, y, duration=step_duration)

使用方式

直接调用这个函数替代原生的pyautogui.moveTo:

human_like_move_to(500, 500, duration=2.5)

方案2:分离X/Y轴的缓动曲线

通过给X/Y轴分配不同的缓动曲线,让鼠标移动路径呈现自然的曲线效果:

import pyautogui
import random

def curved_move_to(target_x, target_y, duration=2, num_steps=30):
    start_x, start_y = pyautogui.position()
    # 为X/Y轴随机选择不同的缓动曲线
    x_tween = random.choice([pyautogui.easeInQuad, pyautogui.easeOutQuad, pyautogui.easeInOutQuad])
    y_tween = random.choice([pyautogui.easeInQuad, pyautogui.easeOutQuad, pyautogui.easeInOutQuad])
    
    step_duration = duration / num_steps
    for i in range(num_steps + 1):
        t = i / num_steps
        # 对X/Y轴分别应用缓动
        eased_x = x_tween(t)
        eased_y = y_tween(t)
        
        current_x = start_x + (target_x - start_x) * eased_x
        current_y = start_y + (target_y - start_y) * eased_y
        
        if i > 0:
            pyautogui.moveTo(current_x, current_y, duration=step_duration)

关键逻辑说明

  • 补间函数的核心是接收0~1的进度值t,返回0~1的调整后进度,用来控制移动的速度变化。
  • 方案1的随机偏移随剩余距离动态调整,模拟人类接近目标时的精准控制;方案2通过分离X/Y轴缓动,生成自然的曲线路径。

内容的提问来源于stack exchange,提问作者nlouis56

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 05:32:36