How to save a canvas as PNG in Selenium?

后端 未结 1 1583
有刺的猬
有刺的猬 2020-12-29 08:05

I am trying to save a canvas element as a png image. This is my code right now but, unfortunately, it does not work:

import time
from selenium import webdriv         


        
相关标签:
1条回答
  • 2020-12-29 09:00

    You could call HTMLCanvasElement.toDataURL() to get the canvas as PNG base64 string. Here is a working example:

    import base64
    from selenium import webdriver
    
    driver = webdriver.Chrome()
    driver.get("http://curran.github.io/HTML5Examples/canvas/smileyFace.html")
    
    canvas = driver.find_element_by_css_selector("#canvas")
    
    # get the canvas as a PNG base64 string
    canvas_base64 = driver.execute_script("return arguments[0].toDataURL('image/png').substring(21);", canvas)
    
    # decode
    canvas_png = base64.b64decode(canvas_base64)
    
    # save to a file
    with open(r"canvas.png", 'wb') as f:
        f.write(canvas_png)
    
    0 讨论(0)
提交回复
热议问题