下载 python 剧作家的当前图像

Download currnet image with python playwright

是否可以用 Playwright 制作这样的东西:

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))

我更喜欢 playwright 而不是 selenium,但找不到 Playwright 的方法。

我尝试了这个并且成功了(我使用了元素处理程序而不是 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))