Playwright反检测优化与规避方法

是的,Playwright 可以通过 Chrome DevTools Protocol (CDP) 连接已打开的浏览器实例,这种方式能更好地模拟真实用户行为。以下是具体实现方案:


方法一:手动接管已打开的浏览器

实现步骤:

  1. 手动启动浏览器(带调试端口)
    在终端执行以下命令启动 Chrome(示例):

    # Windows
    "C:\Program Files\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 --user-data-dir=./chrome_profile
    
    # Mac
    /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 --user-data-dir=./chrome_profile
    
  2. Playwright 连接现有实例

    from playwright.async_api import async_playwright
    
    async def main():
        async with async_playwright() as p:
            # 通过 CDP 连接已打开的浏览器
            browser = await p.chromium.connect_over_cdp("http://localhost:9222")
            context = browser.contexts[0]
            page = await context.new_page()
            
            # 执行操作
            await page.goto("https://zhihu.com")
            print(await page.title())
            
            # 保持浏览器打开(不要关闭)
            # awai

你可能感兴趣的:(我的学习笔记,自动化,python)