6

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

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

测试01.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 会话。此代码应该打开另一个浏览器窗口,但它没有按预期工作:

测试02.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.
4

1 回答 1

7

如何保持浏览器运行

你只需要使用autoClose标志,这里是文档

autoClose (bool):脚本完成时自动关闭浏览器进程。默认为真。

在这种情况下,您的 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 会议

这里是:

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 创建其他会话似乎不是一个好主意,因为browser._contexts不会更新并且会变得不一致。它也Browser.createIncognitoBrowserContext可能满足您的需求,而无需求助于 CDP

于 2018-10-30T19:32:07.697 回答