# -*- coding: utf-8 -*-
"""用 Playwright 启动 Chrome 并连接到 CDP"""
import sys
import subprocess

result = subprocess.run(['pip', 'show', 'playwright'], capture_output=True, text=True)
if result.returncode != 0:
    print("Installing playwright...")
    subprocess.run([sys.executable, '-m', 'pip', 'install', 'playwright', '-q'], check=True)
    subprocess.run([sys.executable, '-m', 'playwright', 'install', 'chromium'], check=True)

from playwright.sync_api import sync_playwright

print("Starting Chromium...")
p = sync_playwright().start()
browser = p.chromium.launch(
    headless=False,
    args=[
        '--remote-debugging-port=9223',
        '--no-first-run',
        '--no-default-browser-check',
    ]
)
print(f"Browser launched! {len(browser.contexts)} contexts")
page = browser.new_page()
page.goto('https://baijiahao.baidu.com')
print(f"URL: {page.url}")

# Keep browser open
print("Press Ctrl+C to exit...")
import time
while True:
    time.sleep(1)
