-
Notifications
You must be signed in to change notification settings - Fork 830
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Question]: Download currnet image with python playwright #1189
Labels
Comments
You can do it like that: import base64
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto('https://playwright.dev')
image_element = page.locator('.main-wrapper img').nth(0)
image_b64 = image_element.evaluate("""element => {
var cnv = document.createElement('canvas');
cnv.width = element.naturalWidth;
cnv.height = element.naturalHeight;
cnv.getContext('2d').drawImage(element, 0, 0, element.naturalWidth, element.naturalHeight);
return cnv.toDataURL().substring(22)
}""")
with open('playwright.png', 'wb') as f:
f.write(base64.b64decode(image_b64))
browser.close() or in JS just for reference: // @ts-check
const playwright = require('playwright');
const fs = require('fs');
(async () => {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
await page.goto('https://playwright.dev/');
const image = page.locator(".main-wrapper img").nth(0);
const imageData = await image.evaluate(element => {
var cnv = document.createElement('canvas');
cnv.width = element.naturalWidth;
cnv.height = element.naturalHeight;
cnv.getContext('2d').drawImage(element, 0, 0, element.naturalWidth, element.naturalHeight);
return cnv.toDataURL().substring(22)
});
fs.writeFileSync('image.png', imageData, 'base64');
await browser.close();
})(); |
Ahh... Thanks for that. It solved my problem. |
@agent666 the draw image's size is larger than the size of the image origin. Could you solve this problem? |
If the image you want to save is dynamically generated or a gif, you can also register a response handler and get the image content from response body, example: def handler(response):
content = response.body()
with open(filepath, "wb") as file:
file.write(content)
page.on("response", hander) |
This gives me
Any ways to work around that? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Your question
Is it possible to make something like this with Playwright:
I prefer playwright over selenium but can't find a way with Playwright.
The text was updated successfully, but these errors were encountered: