Rayrun

How do I use Playwright's Screenshots API to save an image without making another request to the image server?

Answer

Saving Images with Playwright's Screenshots API

You can save an <img> without making another request to the image server using Playwright's Screenshots API. This API lets you capture screenshots and save them as files. Here's how you can do it:

await page.screenshot({ path: 'screenshot.png' })

This line of code captures a screenshot of the current page and saves it as a PNG file named "screenshot.png".

Full-Page Screenshots

If you want to capture a full-page screenshot of a scrollable page, use the fullPage option:

await page.screenshot({ path: 'screenshot.png', fullPage: true })

Element Screenshots

To capture a screenshot of a specific element on the page, use the page.locator() function:

await page.locator('.header').screenshot({ path: 'screenshot.png' })

In this example, .header is a CSS selector for the desired element.

Capturing Screenshots into Buffers

Playwright also lets you capture screenshots into buffers. Instead of writing into a file directly, you can get a buffer with the image:

const buffer = await page.screenshot()

You can then post-process this buffer or pass it on for further usage or analysis.

In summary, Playwright's Screenshots API provides various ways to save <img> elements without making another request to the image server. For more tips on using Playwright, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

References

Thank you!
Was this helpful?
Still have questions?

If you still have questions, please ask a question and I will try to answer it.

Related Discord Threads

Related Questions

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.