Home > OS >  Run playwright in interactive mode in python
Run playwright in interactive mode in python

Time:08-08

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 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'

CodePudding user response:

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)
  • Related