如何在Playwright中实现类人类慢速输入?
解决Playwright fill方法输入过快的类人类输入方案
Playwright的fill方法是直接给输入框赋值,跳过了真实的按键输入流程,所以速度远超人类。想要实现类人类的输入速度,推荐以下两种实用方案:
1. 使用原生type方法(最简便)
type方法会模拟逐个字符的按键输入,支持设置每个字符的输入延迟,完美贴合人类打字节奏。
示例代码:
// 每个字符间隔100毫秒输入,接近普通人类打字速度 await page.type('#username-input', 'john_doe', { delay: 100 });
如果想要更真实的随机节奏,可以结合随机延迟:
const randomDelay = () => Math.floor(Math.random() * 100) + 50; // 生成50-150毫秒的随机延迟 await page.type('#email-input', 'john@example.com', { delay: randomDelay() });
2. 自定义类人类输入函数(更逼真)
如果需要模拟更真实的人类行为(比如偶尔打错字再删除、随机停顿思考),可以封装一个自定义函数:
async function humanLikeType(page, selector, text) { // 先聚焦目标输入框 await page.focus(selector); const minCharDelay = 40; const maxCharDelay = 160; const mistakeChance = 0.03; // 3%的概率模拟输入错误 for (const char of text) { // 生成字符输入的随机延迟 const delay = Math.floor(Math.random() * (maxCharDelay - minCharDelay + 1)) + minCharDelay; await page.keyboard.type(char, { delay }); // 模拟偶尔打错字并修正 if (Math.random() < mistakeChance) { await page.keyboard.type('x', { delay: Math.floor(Math.random() * 50) + 30 }); await page.keyboard.press('Backspace', { delay: Math.floor(Math.random() * 40) + 20 }); } // 偶尔加入短暂停顿,模拟思考过程 if (Math.random() < 0.1) { await page.waitForTimeout(Math.floor(Math.random() * 500) + 200); } } } // 使用示例 await humanLikeType(page, '#password-input', 'MySecurePass123!');
注意事项
type方法会触发输入框的input、keydown、keyup等原生事件,比fill更不容易被反爬机制识别;- 延迟参数不要设置得过于规律,随机范围更贴近真实人类行为;
- 如果输入框有自动补全或实时验证逻辑,
type方法能更好地触发这些交互,避免出现和手动操作不一致的情况。
内容的提问来源于stack exchange,提问作者Chris Hansen
相关产品推荐
相关产品推荐

