Skip to content
Advertisement

Download currnet image with python playwright

Is it possible to make something like this with Playwright:

https://stackoverflow.com/a/52692041

import base64
img_base64 = browser.execute_script("""
    var ele = arguments[0];
    var cnv = document.createElement('canvas');
    cnv.width = ele.width; cnv.height = ele.height;
    cnv.getContext('2d').drawImage(ele, 0, 0);
    return cnv.toDataURL('image/jpeg').substring(22);    
    """, browser.find_element_by_xpath("//your_xpath"))
with open(r"image.jpg", 'wb') as f:
    f.write(base64.b64decode(img_base64))

I prefer playwright over selenium but can’t find a way with Playwright.

Advertisement

Answer

I tried this and it worked (I used an element handler instead of arguments[0]):

selector = page.query_selector('.my-image')
img_base64 = page.evaluate("""(selector_handle) => {
    var cnv = document.createElement('canvas');
    cnv.width = 300; cnv.height = 300;
    cnv.getContext('2d').drawImage(selector_handle, 0, 0);
    return cnv.toDataURL('image/jpeg').substring(22);
}""", selector)
with open(r"image.jpg", 'wb') as f:
    f.write(base64.b64decode(img_base64))
Advertisement