3

I want to use playwright-python to fill some forms automatically. And then double check the filling before submit. But it always close the browser by the end of the code running. Even if I used the handleSIGHUP=False, handleSIGINT=False, handleSIGTERM=False launch arguments, and didn't use any page.close() or browser.close() in my code, it still close the browser after the code finished.

Does anyone know how to do it?

Kaol
  • 353
  • 2
  • 5
  • 15

1 Answers1

2

The browser is started by the python script, so it will end, when the script ends.
So you need to keep the script alive.
For the async part it is a bit tricky. I assume you have same kind of: asyncio.get_event_loop().run_until_complete(main())

so in the async main routine you need to keep the async loop running:

e.g. waiting for the keyboard:

import asyncio
from playwright.async_api import async_playwright
from playwright.async_api import Page

async with async_playwright() as p:
    async def main(run_forever: bool):
        browser = await p.__getattribute__(C.BROWSER.browser).launch(headless=False, timeout=10000)
        page = await browser.new_page()
        if run_forever:
            print('Press CTRL-D to stop')
            reader = asyncio.StreamReader()
            pipe = sys.stdin
            loop = asyncio.get_event_loop()
            await loop.connect_read_pipe(lambda: asyncio.StreamReaderProtocol(reader), pipe)
             async for line in reader:
                 print(f'Got: {line.decode()!r}')
        else:
            browser.close()
HolgT
  • 663
  • 5
  • 17