Run playwright in interactive mode in Python
Asked Answered
J

1

5

I was using playwright to scrape pages using Python. I know how to do the same using a script, but I was trying this in an interactive mode.

from playwright.sync_api import Playwright, sync_playwright, expect
import time

def run(playwright: Playwright) -> None:
    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()

    page = context.new_page()
    page.goto("https://www.wikipedia.org/")

    context.close()
    browser.close()
with sync_playwright() as playwright:
    run(playwright)

I tried to do this in interactive mode as:

>>> from playwright.sync_api import Playwright, sync_playwright, expect
>>> playwright = sync_playwright()
>>> browser = playwright.chromium.launch(headless=False)

But this gave me an error:

Traceback (most recent call last):
  File "C:\Users\hpoddar\AppData\Local\Programs\Python\Python310\lib\idlelib\run.py", line 578, in runcode
    exec(code, self.locals)
  File "<pyshell#2>", line 1, in <module>
AttributeError: 'PlaywrightContextManager' object has no attribute 'chromium'
Jactitation answered 7/8, 2022 at 13:22 Comment(2)
with sync_playwright() as playwright: is not the same as "playwright = sync_playwright()" . playwright object is only valid INSIDE the context manager opened by "with" docs.python.org/3/reference/datamodel.html#context-managersIrish
@PmpP. check out Charchit's answer, that's what I exactly needed https://mcmap.net/q/1928557/-run-playwright-in-interactive-mode-in-pythonJactitation
C
12

Use the .start() method:

>>> from playwright.sync_api import Playwright, sync_playwright, expect
>>> playwright = sync_playwright().start()
>>> browser = playwright.chromium.launch(headless=False)
>>> page = browser.new_page()

Alternatively, if you just want an interactive browser, and don't care about an interactive shell, you can also use the wait_for_timeout function instead (only applicable on Page objects) and set the timeout to a high value:

from playwright.sync_api import sync_playwright

with sync_playwright() as playwright:
    browser = playwright.chromium.launch(headless=False)
    page = browser.new_page()
    page.wait_for_timeout(10000)
Catastrophism answered 7/8, 2022 at 21:12 Comment(2)
is there any method like sync_playwright().stop() ?Jactitation
@Himanshuman just do playwright.stop()Catastrophism

© 2022 - 2025 — McMap. All rights reserved.