Playwright 模拟鼠标键盘示范


py
# pip install playwright
# playwright install
# 以上两行是安装与浏览器下载指令  # 中文注释

import asyncio
import random
from playwright.async_api import async_playwright  # 中文注释

async def human_type(locator, text: str,
                     min_delay_ms: int = 50,
                     max_delay_ms: int = 150,
                     typo_chance: float = 0.04):
    """
    逐字符输入:随机延迟 + 偶发错字后退格  # 中文注释
    """
    for ch in text:
        # 偶尔先打错一个字符,再退格,模拟人类纠错  # 中文注释
        if typo_chance > 0 and random.random() < typo_chance:
            wrong = random.choice("abcdefghijklmnopqrstuvwxyz")
            await locator.type(wrong, delay=random.randint(min_delay_ms, max_delay_ms))  # 中文注释
            await locator.press("Backspace")  # 中文注释

        # 正常输入当前字符  # 中文注释
        await locator.type(ch, delay=random.randint(min_delay_ms, max_delay_ms))  # 中文注释

        # 偶发短暂停顿,模拟思考/犹豫  # 中文注释
        if random.random() < 0.1:
            await asyncio.sleep(random.uniform(0.05, 0.3))  # 中文注释

async def realistic_click(page, locator):
    """
    更“像人”的点击:滚动到可见 + 鼠标平滑移动 + 轻微停顿后点击  # 中文注释
    """
    await locator.scroll_into_view_if_needed()  # 保证元素在视口中  # 中文注释
    box = await locator.bounding_box()
    if not box:
        raise RuntimeError("元素不可见,无法点击")  # 中文注释

    # 在元素区域内随机一点,避免每次都点正中心  # 中文注释
    target_x = box["x"] + box["width"] * random.uniform(0.35, 0.65)
    target_y = box["y"] + box["height"] * random.uniform(0.35, 0.65)

    # 平滑移动:更多 steps 更像手动移动鼠标  # 中文注释
    await page.mouse.move(target_x, target_y, steps=random.randint(15, 35))  # 中文注释
    await page.wait_for_timeout(random.randint(60, 180))  # 微停顿  # 中文注释
    await page.mouse.down()  # 中文注释
    await page.wait_for_timeout(random.randint(20, 80))   # 点击按下停留  # 中文注释
    await page.mouse.up()    # 中文注释

async def main():
    async with async_playwright() as p:
        # slow_mo 会让每个动作放慢一点,更像人类节奏  # 中文注释
        browser = await p.chromium.launch(headless=False, slow_mo=50)  # 中文注释
        context = await browser.new_context(locale="en-US", timezone_id="Asia/Tokyo")  # 可设你的语言/时区  # 中文注释
        page = await context.new_page()  # 中文注释

        await page.goto("https://www.microsoft.com/en-us/edge")  # 随便找个可输入的网站示例  # 中文注释

        # 找一个搜索框或输入框(只是示例,实际请按你的页面选择器修改)  # 中文注释
        search = page.locator("input[type='search'], input[type='text']").first  # 中文注释
        await realistic_click(page, search)  # 模拟人类点击输入框  # 中文注释

        # 逐字符输入并模拟人类纠错  # 中文注释
        await human_type(search, "playwright human-like typing demo")  # 中文注释

        # 模拟按下 Enter 提交  # 中文注释
        await search.press("Enter")  # 中文注释

        # 模拟滚轮浏览一下页面  # 中文注释
        for _ in range(random.randint(3, 6)):
            await page.mouse.wheel(0, random.randint(200, 800))  # 往下滚动一点  # 中文注释
            await asyncio.sleep(random.uniform(0.2, 0.6))        # 停顿  # 中文注释

        await asyncio.sleep(3)  # 观察几秒  # 中文注释
        await browser.close()   # 中文注释

if __name__ == "__main__":
    asyncio.run(main())  # 中文注释