使用 Python-playwright,如何在不保存到磁盘或使用临时文件的情况下制作屏幕截图?

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

我想使用 Python Playwright 制作屏幕截图并将该屏幕截图交给 REST API。我找到了一个示例 here,它制作了屏幕截图并将其保存到文件中:

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()

如何在不将屏幕截图保存到磁盘或使用临时文件并将其传递给 REST 调用的情况下制作屏幕截图?

您根本不需要将图像保存到文件中 (cmp.screenshot documentation),而是可以将其简单地存储在一个变量中,例如 img = page.screenshot()。然后您可以将该变量传递给您的 REST 请求。我在下面的示例中使用 requests 模块,POST 请求被简化并且可能需要一些额外的参数(取决于您的 API)或者例如不同浏览器类型的不同 URL:

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()

如果您出于某种原因真的想将图像保存到临时文件(据我了解您的用例,这并不是真正必要的),您可以例如使用 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()