Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep browser opening by the end of the code running with playwright-python?

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?

like image 845
Kaol Avatar asked Oct 18 '25 11:10

Kaol


1 Answers

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()
like image 56
HolgT Avatar answered Oct 21 '25 10:10

HolgT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!