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

5

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?

Benefice answered 20/1, 2021 at 3:30 Comment(1)
in headed mode (headless=False), you can use page.pause(), it will show the playwright console. playwright.dev/python/docs/api/class-page#page-pauseSamala
I
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()
Incommensurate answered 9/2, 2021 at 14:34 Comment(0)
E
1

My use case is for Playwright to just be some browser automation in addition to user tasks. As such, I want my browser to be independent of my Playwright script. By using Chrome DevTools Protocol (CDP), I can have an independent browser session that can still be automated with Playwright.

Reference: Is there a way to connect to my existing browser session using playwright

The summary of my solution is:

  1. Check if browser is listening on port 9222
  2. If not, use subprocess.Popen to spawn a browser so it remains open after script finishes. Use option --remote-debugging-port=9222 so that Playwright can connect to the browser
  3. Connect to existing or just spawned browser over CDP

The code looks like

import socket
import subprocess

from playwright.sync_api import sync_playwright

# Check for existing browser listening on port 9222
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    try:
        s.connect(('localhost', 9222))
        is_socket = True
    except socket.error as e:
        is_socket = False

print('Found socket:', is_socket)
# If browser doesn't exist, spawn a new one w/ CDP on port 9222
if not is_socket:
    subprocess.Popen([
        "<PATH TO CHROME>/chrome.exe",
        "--remote-debugging-port=9222",
        ])

# Connect to the browser w/ CDP
with sync_playwright() as p:
    
    browser = p.chromium.connect_over_cdp("http://localhost:9222")
    context = browser.contexts[0]
    page = context.pages[0]    
Endmost answered 3/7, 2024 at 3:16 Comment(0)
R
0

get see worked link

Context:

Playwright Version: 1.16 Operating System: Windows Node.js version: 14.18.1 Browser: All Overview There are multiple ways to turn on the Inspector, as explained in https://playwright.dev/docs/inspector As per docs, when we set "PWDEBUG", it also disables the timeout, by setting it to 0. This is a good idea, as it allows the user to click around the inspector without a time limit.

However, this is not the case with page.pause(). This option also opens the inspector, but the timeout is not set to 0, thus the inspector will force exit after 30s with e.g.

Slow test: tests\my_test.test.js (30s)

The same behavior is mentioned in a Feature request here: #10132 And I believe it should be fixed to match the default behaviour of other options, at least for consistency reasons. For example, in Java binding, page.pause() does not require timeOut to be explicitly disabled.

Receiver answered 8/2, 2023 at 12:34 Comment(0)
N
0

you can use code below

while True:
    page.wait_for_timeout(10000)
Necessarily answered 2/9, 2023 at 9:19 Comment(0)
B
0

For me this solution works best.This waits for close event from user

page.wait_for_event("close" , timeout = 0)

Pass timeout=0 to prevent browser from closing after sometime

Boatbill answered 12/6, 2024 at 1:56 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.