Tuesday, December 5, 2023

Saving screenshot of web element using selenium

 It is common to save screenshot of web pages using selenium, is it really possible to save a screenshot of a single web element on a page?

Recently, I found myself in a situation where I have to save the screenshot of an image map from several web pages.


Let see how it is done.

I want to save the screenshot of the SVG map on this web page as seen below. 


There are couple of ways to get this done including screenshotting the entire browser window or downloading the SVG map to local directory. All these are not suitable for this specific use case, so we have to screenshot just the map element and save it locally as a png image file. This is exactly what we wanted and fortunately, selenium can do it for us as seen below:-

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
url = 'https://www.europages.co.uk/EURO-EXPORT-PROJECTS/00000005495550-001.html'
path = r"chromedriver-win64\chromedriver.exe"

service = Service(executable_path=path)
driver = webdriver.Chrome(service=service)

driver.get(url)

# Take screenshot of entire window...
# driver.save_screenshot('ss.png')


# Take screenshot of just the map element....
canvas_map = driver.find_element(By.XPATH, '//*[@id="app"]/div[1]/div[1]/div/div[2]/div[1]/div/div[2]/section[5]/div[1]/h3')
canvas_map.screenshot('map_file_2.png')

The saved file looks like so...

Happy coding!