您根本不需要将图像保存到文件(cmp. screenshot 文档),而是可以简单地将其存储在变量中,例如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
模块并创建一个命名的临时文件(cmp。如何使用 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()