playwright连接本地浏览器(调试模式)

holmes8699 投稿日時は 11 日前 49 表示


import asyncio
import os
import subprocess
import time
import sys
from playwright.async_api import async_playwright

async def connect_to_chrome_or_launch():
    """连接到已运行的Chrome(调试模式)或启动新的Chrome"""
    try:
        async with async_playwright() as p:
            # 尝试连接到已运行的Chrome实例
            try:
                print("正在尝试连接到已运行的Chrome浏览器(调试模式)...")
                browser = await p.chromium.connect_over_cdp("http://127.0.0.1:9222")
                print("已成功连接到运行中的Chrome浏览器")
            except Exception as conn_error:
                print(f"无法连接到已运行的Chrome: {str(conn_error)}")
                print("正在尝试自动启动Chrome浏览器并开启调试模式...")
                
                # 查找Chrome浏览器路径
                chrome_paths = [
                    "C:\Program Files\Google\Chrome\Application\chrome.exe",
                    "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
                    # 添加其他可能的Chrome路径
                ]
                
                chrome_path = None
                for path in chrome_paths:
                    if os.path.exists(path):
                        chrome_path = path
                        break
                
                if not chrome_path:
                    print("错误: 未找到Chrome浏览器安装路径。")
                    print("请手动安装Chrome浏览器,或在代码中添加Chrome的安装路径。")
                    return
                
                # 启动Chrome并开启调试模式
                try:
                    # 使用--user-data-dir创建独立配置,避免影响默认配置
                    user_data_dir = os.path.join(os.getenv('TEMP'), 'chrome_debug_profile')
                    subprocess.Popen([
                        chrome_path,
                        '--remote-debugging-port=9222',
                        f'--user-data-dir={user_data_dir}',
                        '--no-first-run',
                        '--no-default-browser-check'
                    ], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                    
                    # 等待Chrome启动
                    print("正在启动Chrome浏览器...")
                    time.sleep(3)
                    
                    # 尝试连接到新启动的Chrome
                    browser = await p.chromium.connect_over_cdp("http://127.0.0.1:9222")
                    print("已成功启动并连接到Chrome浏览器")
                except Exception as launch_error:
                    print(f"启动Chrome失败: {str(launch_error)}")
                    print("\n请尝试手动启动Chrome:")
                    print(f"1. 打开命令提示符")
                    print(f"2. 输入命令: \"{chrome_path}\" --remote-debugging-port=9222")
                    print(f"3. 然后重新运行此程序")
                    return
            
            # 获取现有的页面,如果没有则创建新页面
            try:
                if browser.contexts:
                    pages = browser.contexts[0].pages
                    if pages:
                        page = pages[0]  # 使用第一个页面
                    else:
                        page = await browser.contexts[0].new_page()  # 创建新页面
                else:
                    context = await browser.new_context()
                    page = await context.new_page()
            except Exception as page_error:
                print(f"获取或创建页面失败: {str(page_error)}")
                return
            
            # 访问网易163
            try:
                await page.goto('https://www.baidu.com', wait_until='networkidle')
                print("已成功访问baidu网站")
            except Exception as goto_error:
                print(f"访问网站失败: {str(goto_error)}")
            
            print("请在浏览器中进行操作,程序会保持连接直到手动中断")
            
            # 暂停执行,让用户可以在浏览器中交互
            try:
                await page.pause()
            except KeyboardInterrupt:
                print("用户中断程序")
            
            print("已断开与浏览器的连接")
    except Exception as e:
        print(f"发生未预期的错误: {str(e)}")
        print("\n建议的解决方案:")
        print("1. 确保已安装Playwright: pip install playwright")
        print("2. 确保网络连接正常")
        print("3. 检查防火墙设置,确保端口9222未被阻止")

if __name__ == "__main__":
    # 运行异步函数
    try:
        asyncio.run(connect_to_chrome_or_launch())
    except KeyboardInterrupt:
        print("程序已退出")