3

I'm creating a web automation that I need to keep the browser open, but since playwright library only has the getting started showing the code including the "with" statement every time the script it's finished the browser close itself. I know I could quickly fix this with time(100), but this doesn't seem like the best practice. I've tried to create do something similar, without the with statement, but it keeps closing the browser. How can I fix this issue and keep the browser open?

Please see my code below:

from playwright.sync_api import sync_playwright

p = sync_playwright().start()
browser = p.chromium.launch(headless=False)
page = browser.new_page()
page.goto('https://www.google.com/')
p.stop()
ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • 1
    Does this answer your question? [can i run playwright outside of 'with'?](https://stackoverflow.com/questions/72653869/can-i-run-playwright-outside-of-with) – ggorlen Jul 20 '22 at 18:38

2 Answers2

4

If you don't want to use context managers then you can start the browser without one using the .start() method:

from playwright.sync_api import sync_playwright

p = sync_playwright().start()
browser = p.chromium.launch(headless=False)
page = browser.new_page()
p.stop()

Remember to use the .stop() method once you are done.

Charchit Agarwal
  • 2,829
  • 2
  • 8
  • 20
  • hey, thanks for your answer, but the browser keeps closing the window. Tried to remove the p.stop() line, but didn't work. I need to keep the browser open :/ – python noobie Jul 21 '22 at 19:55
  • 2
    @pythonnoobie update your question with what you tried to do – Charchit Agarwal Jul 21 '22 at 20:19
  • @pythonnoobie Make sure to call `p.stop()` only after doing whatever you need to do, or skip the call entirely if you want to leave the browser open indefinitely. – ggorlen Nov 21 '22 at 18:55
0

Playwright has its own waits. My code is asyncronous, but the playwright API is similar for syncronous code.

async def main():
    apw = await async_playwright().start()
    browser: Browser = await apw.firefox.launch(headless=False)
    page = await browser.new_page()
    await page.goto('https://avito.ru')
    await page.wait_for_timeout(10000)
    apw.stop()

asyncio.get_event_loop().run_until_complete(main()) 
BouygudSt
  • 71
  • 2
  • 2