Rayrun
← Back to Discord Forum

Save already loaded image

Is there a way to save an <img> without making another request to the image server?

This thread is trying to answer question "Is there a way to save an <img> without making another request to the image server?"

3 replies

Ive seen one approach on playwright-python github (https://github.com/microsoft/playwright-python/issues/1189), which runs some JS to convert image to base64, but that didnt work for me as it produces Error: The operation is insecure error

i assume due to the image hosting domain being different from the website viewed

i tried setting BypassCSP option to the page i create, but that didnt help either

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.

Related Discord Threads

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 [email protected].