python playwright连接debug浏览器
时间: 2023-10-10 11:08:55 浏览: 113
Playwright _ API.pdf
为了连接 debug 浏览器,首先需要安装 playwright 和浏览器的 debug 版本。然后使用以下代码进行连接:
```python
from playwright.sync_api import Playwright, async_playwright
async def connect_to_browser() -> Playwright:
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=False) # 使用非 headless 模式启动浏览器
context = await browser.new_context()
page = await context.new_page()
# 连接浏览器的 WebSocket 调试端口
await page.goto("chrome://version")
version = await page.textContent(".version")
debugger_url = f"ws://{version.split(' ')[-1]}/devtools/browser/{page.context._connection._sessionId}"
await context.close()
return await playwright.chromium.connect_over_websocket(debugger_url=debugger_url, timeout=3000)
browser = connect_to_browser().result()
```
这段代码会启动一个非 headless 模式的 Chromium 浏览器,并在浏览器中输入 `chrome://version` 进入版本信息页面。然后通过解析页面上的版本号,得到浏览器的 WebSocket 调试端口地址,再通过 playwright 的 `connect_over_websocket` 方法连接到浏览器并返回浏览器对象。
阅读全文