Search code examples
pythonscreenshottemporary-filesplaywrightplaywright-python

Using Python-playwright, how do I make a screenshot without saving it to disk or using a temporary file?


I want to make a screenshot using Python Playwright and hand that screenshot to a REST API. I found an example here that makes a screenshot and saves it to a file:

from playwright import sync_playwright
with sync_playwright() as p:
    for browser_type in [p.chromium, p.firefox, p.webkit]:
        browser = browser_type.launch()
        page = browser.newPage()
        page.goto('https://scrapingant.com/')
        page.screenshot(path=f'scrapingant-{browser_type.name}.png')
        browser.close()

How can I make the screenshot without saving it to disk or using a temporary file and pass it to a REST call?


Solution

  • You do not need to save the image to a file at all (cmp. screenshot documentation), but instead can simply store it in a variable, like img = page.screenshot(). You can then pass that variable to your REST request. I use the requests module in the example below, the POST request is simplified and may require some additional parameters (depending on your API) or for instance different URLs for the different browser types:

    from playwright import sync_playwright
    import requests
    
    with sync_playwright() as p:
        for browser_type in [p.chromium, p.firefox, p.webkit]:
            browser = browser_type.launch()
            page = browser.newPage()
            page.goto('https://scrapingant.com/')
            # save screenshot to var
            img = page.screenshot() 
            # pass var directly to your request
            files = {'image': img, 'content-type': 'image/png'}
            requests.post('http://yourresturl.com', files=files)
            browser.close()
    

    If you really wanted to save the image to a temporary file for some reason (which, as I understand your use case, is not really necessary), you could e.g. use the tempfile module and create a named temporary file (cmp. How to use tempfile.NamedTemporaryFile()?):

    from playwright import sync_playwright
    import tempfile
    import requests
    
    tf = tempfile.NamedTemporaryFile(suffix='.png')
    
    with sync_playwright() as p:
        for browser_type in [p.chromium, p.firefox, p.webkit]:
            browser = browser_type.launch()
            page = browser.newPage()
            page.goto('https://scrapingant.com/')
            # save screenshot to temporary file
            page.screenshot(path=tf.name)
            # send request loading temporary file
            requests.post('http://myresturl.com', {'media': open(tf.name, 'rb')})
            browser.close()        
    
    # close temporary file
    tf.close()