Getting the image of an element in a website with Selenium

Question:

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

||

Answers:

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 webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by 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'
opts.add_argument("--headless")
opts.add_argument('--no-sandbox')

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]"
opts.add_argument(user_agent)

# 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)

browser.get('https://www.robotreboot.com/challenge')

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:
    f.write(canvas_png)
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.