import asyncio
# Correct import: import async_playwright
from playwright.async_api import async_playwright
async def connect_and_control_playwright():
# Correct usage: async with async_playwright() as p:
async with async_playwright() as p:
print("Playwright: Initializing...")
try:
# 连接到已开放 9222 端口的浏览器
# 注意:Playwright 默认连接到 'ws://localhost:9222/devtools/browser'
# 你可能需要根据实际情况调整 URL。
# 通常,连接到 HTTP 端口即可,Playwright 会自动发现 WebSocket URL。
browser = await p.chromium.connect_over_cdp("http://localhost:9222")
print("Playwright: Successfully connected to browser via CDP.")
# 获取默认的上下文(context)
# 对于 connect_over_cdp,通常会有一个默认的浏览器上下文
# 如果没有,则创建一个新的
if browser.contexts:
context = browser.contexts[0]
print("Playwright: Using existing browser context.")
else:
context = await browser.new_context()
print("Playwright: Created a new browser context.")
# 尝试获取现有页面,如果存在则复用,否则打开新页面
pages = context.pages
if pages:
page = pages[0] # 复用第一个现有页面
print("Playwright: Reusing existing page.")
else:
page = await context.new_page() # 如果没有页面,则打开新页面
print("Playwright: No existing pages found, opened a new page.")
# 导航到指定 URL
await page.goto("https://www.google.com")
print(f"Playwright: Navigated to {page.url}")
# 获取页面标题
title = await page.title()
print(f"Playwright: Page title is '{title}'")
# 截图并保存
await page.screenshot(path="playwright_screenshot.png")
print("Playwright: Screenshot saved as 'playwright_screenshot.png'")
except Exception as e:
print(f"Playwright Error: {e}")
print("Please ensure your Chrome browser is running with --remote-debugging-port=9222.")
print("Example: google-chrome --remote-debugging-port=9222 --user-data-dir=/tmp/my-chrome-profile")
finally:
# 确保在任何情况下都尝试关闭浏览器连接
if 'browser' in locals() and browser:
await browser.close()
print("Playwright: Disconnected from the browser.")
if __name__ == "__main__":
asyncio.run(connect_and_control_playwright())
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)