Getting the image of an element in a website with Selenium


In this website there is a board at the center. If you click on it with the right mouse button, it is possible to copy/save its image. In this sense, I want to code with Selenium a way to get this image. However, the board’s element is only given by

<canvas width="640" height="640" class="board-canvas"></canvas>

Which doesn’t have any reference to the image itself, such as an URL of it, for example. So how would it be possible to get the board’s image knowing its element?

Asked By: ordptt



Since it is a canvas, we can use the command HTMLCanvasElement.toDataURL().

Returns the image as a base64-encoded string. You then simply decode it and write it to a file.

This is a complete example of reproducible code:

from selenium import webdriver
from import ChromeDriverManager
from import Service
from import Options
from import By
import base64

# It is not mandatory to specify all this, but it is strongly recommended for any web scraping software
opts = Options()

# make web scraping 'invisible'

user_agent = "user-agent=[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36]"

# ChromeDriverManager ensures no webdriver recovery issues under any supported operating system
# If you don't like this way, use the classic webdriver with the system path
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=opts)


canvas = browser.find_element(By.CSS_SELECTOR, "canvas")

# get the canvas as a PNG base64 string
canvas_base64 = browser.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:
Answered By: Giuseppe La Gualano
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.