Search code examples
pythonplaywright

sync_playwright().start() seems to hang


Simple code I wrote:

from playwright.sync_api import sync_playwright
print('debug1')

p = sync_playwright().start()
print('debug2')
browser = p.firefox.launch(headless=False)
print('debug3')
page = browser.new_page()
page.goto("http://whatsmyuseragent.org/")
page.screenshot(path="example.png")
browser.close()

And the output I get:

debug1

I am a complete noob in using playwright library, and the program just hangs on the 'sync_playwright().start()' part. I've tried running other example scripts from the internet, and all of them froze on this line. Also I've tried changing browsers and using headless mode, all of them didn't work.


Solution

  • You are supposed to use sync_playwright as a context managers:

    from playwright.sync_api import sync_playwright
    print('debug1')
    
    with sync_playwright() as p:
        print('debug2')
        browser = p.firefox.launch(headless=False)
        print('debug3')
        page = browser.new_page()
        page.goto("http://whatsmyuseragent.org/")
        page.screenshot(path="example.png")
        browser.close()
    

    Output

    debug1
    debug2
    debug3
    

    See playwright documentation for python here

    Edit (specific to OP)

    As a last ditch effort, try these steps in order:

    1. Run pip install -U pip
    2. Run pip uninstall plawyright
    3. Run pip cache remove playwright
    4. Run pip install playwright

    Keep in mind that if you have installed multiple versions of python, use the PATH variable defined for pip for the version of python you want to install playwright in. Lastly, try changing the browser you use with playwright. So instead of browser = p.firefox.launch(headless=False), use browser = p.chromium.launch(headless=False)