如何在Selenium中将画布保存为PNG? [英] How to save a canvas as PNG in Selenium?

查看:818
本文介绍了如何在Selenium中将画布保存为PNG?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 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中查看解决方案。我还希望在截图结束时看到一个不需要裁剪的解决方案。

I would like to see the solution in Python. I would also like to see a solution that does not require cropping at the end of the screenshot.

推荐答案

你可以打电话给 HTMLCanvasElement.toDataURL()将画布作为PNG base64字符串。这是一个工作示例:

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)

这篇关于如何在Selenium中将画布保存为PNG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆