SeleniumAutomation TestingTesting Tools

We can download images with Selenium webdriver in Python. First of all, we shall identify the image that we want to download with the help of the locators like id, class, xpath, and so on.

We shall use the open method for opening the file in write and binary mode (is represented by wb). Then capture the screenshot of the element that we desire to capture with the screenshot_as_png method.

Finally, the captured image must be written to the opened file with the write method. Let us make an attempt to download the image of an element having the below html −

Syntax

with open('Logo.png', 'wb') as file:
file.write(driver.find_element_by_xpath('//*[@alt="I"]').screenshot_as_png)

Example

from selenium import webdriver
#set chromedriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/index.htm");
#open file in write and binary mode
with open('Logo.png', 'wb') as file:
#identify image to be captured
l = driver.find_element_by_xpath('//*[@alt="Tutorialspoint"]')
#write file
file.write(l.screenshot_as_png)
#close browser
driver.quit()

Output

File Logo.png gets created in the project folder.

On opening the file −

Published on 02-Feb-2021 16:36:24