一尘不染

如何在Selenium中将画布另存为PNG?

selenium

我正在尝试将canvas元素另存为png图像。这是我现在的代码,但是不幸的是,它不起作用:

import time
from selenium import webdriver
# From PIL import Imag.


driver = webdriver.Firefox()
driver.get('http://www.agar.io')
driver.maximize_window()
driver.find_element_by_id('freeCoins').click()

time.sleep(2)

# The part below does not seem to work properly.

driver.execute_script('function download_image(){var canvas = document.getElementByTagName("canvas");canvas.toBlob(function(blob) {saveAs(blob, "../images/output.png");}, "image/png");};')

我想看看Python中的解决方案。我还希望在屏幕快照的末尾看到不需要裁剪的解决方案。


阅读 412

收藏
2020-06-26

共1个答案

一尘不染

您可以调用HTMLCanvasElement.toDataURL()将画布作为PNG base64字符串获取。这是一个工作示例:

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)
2020-06-26