问题描述
我想使用 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 并创建一个命名的临时文件 (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.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()