gpt4 book ai didi

Python:在 pyppeteer 中保持打开浏览器并创建 CDPSession

转载 作者:太空宇宙 更新时间:2023-11-03 11:15:21 26 4
gpt4 key购买 nike

我有两个问题暂时无法解决。

1. 我想让浏览器保持运行状态,这样我就可以使用 pyppeteer.launcher.connect() 重新连接函数,但即使我不调用 pyppeteer.browser.Browser.close(),它似乎也立即关闭了.

test01.py:

import asyncio

from pyppeteer import launch, connect

async def fetch():
browser = await launch(
headless=False,
args=['--no-sandbox']
)
print(f'Endpoint: {browser.wsEndpoint}')
await browser.disconnect()

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())

$ python test01.py
Endpoint: ws://127.0.0.1:51757/devtools/browser/00e917a9-c031-499a-a8ee-ca4090ebd3fe
$ curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" http://127.0.0.1:51757
curl: (7) Failed to connect to 127.0.0.1 port 51757: Connection refused

2. 如何创建 CDP session 。这段代码应该会打开另一个浏览器窗口,但它没有按预期工作:

test02.py

import asyncio
import time

from pyppeteer import launch, connect

async def fetch():
browser = await launch(
headless=False,
args=['--no-sandbox']
)
page = await browser.newPage()
cdp = await page.target.createCDPSession()
await cdp.send('Target.createBrowserContext')
time.sleep(5)
await browser.disconnect()

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())

$ python test02.py
Future exception was never retrieved
future: <Future finished exception=NetworkError('Protocol error Target.sendMessageToTarget: Target closed.',)>
pyppeteer.errors.NetworkError: Protocol error Target.sendMessageToTarget: Target closed.

最佳答案

如何保持浏览器运行

你只需要使用autoClose标志,这里是docs :

autoClose (bool): Automatically close browser process when script completed. Defaults to True.

在这种情况下,您的 test01.py 将如下所示:

import asyncio

from pyppeteer import launch, connect

async def fetch():
browser = await launch(
headless=False,
args=['--no-sandbox'],
autoClose=False
)
print(f'Endpoint: {browser.wsEndpoint}')
await browser.disconnect()

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())

CDP session

这里是:

import asyncio
import time

from pprint import pprint

from pyppeteer import launch, connect
from pyppeteer.browser import BrowserContext

async def fetch():
browser = await launch(
headless=False,
args=['--no-sandbox'],
autoClose=False
)
page = await browser.newPage()
cdp = await page.target.createCDPSession()
raw_context = await cdp.send('Target.createBrowserContext')
pprint(raw_context)
context = BrowserContext(browser, raw_context['browserContextId'])
new_page = await context.newPage()
await cdp.detach()
await browser.disconnect()

loop = asyncio.get_event_loop()
loop.run_until_complete(fetch())

灵感来自 Browser.createIncognitoBrowserContext来自 pyppeteer 本身。请注意,通过 CDP 创建额外的 session 似乎不是一个好主意,因为 browser._contexts 不会更新并且会变得不一致。 Browser.createIncognitoBrowserContext 也可能满足您的需求,而无需诉诸 CDP

关于Python:在 pyppeteer 中保持打开浏览器并创建 CDPSession,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52932604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com