简体   繁体   中英

Run playwright in interactive mode in python

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'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM