Run playwright in interactive mode in Python

Question:

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:UsershpoddarAppDataLocalProgramsPythonPython310libidlelibrun.py", line 578, in runcode
    exec(code, self.locals)
  File "<pyshell#2>", line 1, in <module>
AttributeError: 'PlaywrightContextManager' object has no attribute 'chromium'
Asked By: Himanshuman

||

Answers:

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)
Answered By: Charchit