javascript - 如何在 Selenium 中将 Canvas 保存为 PNG?

标签 javascript python selenium canvas png

我正在尝试将 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 中的解决方案。我还希望看到一个不需要在屏幕截图末尾进行裁剪的解决方案。

最佳答案

您可以调用 HTMLCanvasElement.toDataURL() 将 Canvas 作为 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)

关于javascript - 如何在 Selenium 中将 Canvas 保存为 PNG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38316402/

相关文章:

javascript - 如何获取数组中最大的数字和对应的名称?

python - 在 python webkit 中使用 svg 字体

java - cucumber .runtime.CucumberException : java. lang.NoSuchMethodException

python - Selenium Chrome 选项和功能

java - readFully 未使用 Java Nashorn Javascript 引擎定义

c# - 内存效率:Passing Html code of aspx page through codebehind

javascript - 正则表达式 - 不包含某些字符的可打印 ASCII (JS)

Python 制作文件仅在启动时产生 fatal error ?

python - 如何使用 SWIG 生成跨平台界面?

python - 有人知道如何使用 selenium webdriver 识别 shadow dom web 元素吗?