python 下载 canvas里的图片

from selenium import webdriver
import base64
import os
import time


def down_image(canvas_class, name):
    mypath = os.path.dirname((os.path.abspath(__file__)))  
    js = 'return document.getElementsByClassName("{}")[0].toDataURL("image/png");'.format(
        canvas_class)
    image_data = browser.execute_script(js)      # 执行js代码得到图片数据
    image_base64 = image_data.split(",")[1]      # 获得base64编码的图片信息
    image_bytes = base64.b64decode(image_base64)  # 将base64转为bytes类型
    image_png="{}\\{}.png".format(mypath, name)
    with open(image_png, "wb") as f:
        f.write(image_bytes)
    print("图片保存到",image_png)


if __name__ == '__main__':
    browser = webdriver.Chrome(executable_path='chromedriver')
    browser.get("http://localhost/test.html")
    down_image("myCanvas", "temp") 
    down_image("myCanvas2", "temp2")
    time.sleep(1)
    browser.quit()

test.html



 
 
测试 canvas 



Canvas:

静止跨越调用的图片 https://www.w3school.com.cn/i/eg_flower.png 解决跨域问题 https://blog.csdn.net/weixin_40647516/article/details/102660374 js跨越解决方案 https://www.cnblogs.com/chris-oil/p/9609352.html

你可能感兴趣的:(python 下载 canvas里的图片)