如何用Python的pyautogui实现类人类快速逐字自动打字?
实现逼真的逐字打字效果(PyAutoGUI)
嘿,这个问题我之前也折腾过!PyAutoGUI自带的typewrite确实太“顺滑”了,跟直接粘贴没差。要实现逐字输入还保持较快速度,其实只要给每个字符加个随机小延迟就行,甚至可以加点细节让它更像真人打字。
基础版:快速又自然的逐字输入
核心思路就是循环遍历每个字符,每次输入后加个短时间的随机延迟——既保证速度,又有自然的间隔波动,不会像机器那样匀速输出。
import pyautogui import time import random def human_type(text, min_delay=0.05, max_delay=0.15): for char in text: pyautogui.typewrite(char) # 每个字符之间加随机延迟,范围可按需调整 time.sleep(random.uniform(min_delay, max_delay)) # 调用示例 human_type("what i want to type")
这里的min_delay和max_delay控制打字速度:0.05-0.15秒的间隔,大概是每秒6-20个字符,已经相当快了,同时随机波动的延迟会让输入看起来更真实。
进阶版:模拟真人小失误(可选)
如果想更贴近真实的打字行为,可以加个小概率的输入错误再修正——比如偶尔打错相邻键,然后删除重打:
import pyautogui import time import random def super_human_type(text, min_delay=0.05, max_delay=0.15, error_chance=0.03): for char in text: # 3%的概率触发输入错误 if random.random() < error_chance: # 随机选一个相邻键的错误字符 wrong_char = random.choice([chr(ord(char)+1), chr(ord(char)-1)]) pyautogui.typewrite(wrong_char) time.sleep(random.uniform(0.1, 0.2)) # 删除错误字符 pyautogui.press('backspace') # 输入正确字符 pyautogui.typewrite(char) time.sleep(random.uniform(min_delay, max_delay)) # 调用示例 super_human_type("what i want to type")
你可以调整error_chance的值来控制失误频率,0.03就是3%的概率,这个比例比较接近真人的小失误。
几个实用小提示
- 速度自定义:如果想要更快的输入,把
min_delay降到0.03、max_delay设为0.1,速度会非常快但依然保持自然的间隔; - 中文输入注意:如果是输入中文,PyAutoGUI的
typewrite需要配合系统输入法,建议先切换到英文输入英文/符号,或者用输入法的快捷键来切换; - 拒绝固定延迟:一定要用
random.uniform生成随机延迟,固定间隔的话还是会暴露“机器身份”。
内容的提问来源于stack exchange,提问作者Spencer




