How to get image src in Selenium Python?
Selenium Python - Get image src
In this tutorial, you shall learn how to get the value of src attribute of an image element, using Selenium in Python language.
To get the value of src attribute of a given image element in Selenium Python, you can call the get_attribute() method on the image object, and pass 'src' as argument.
image.get_attribute('src')
This function call returns a string value representing the value of src attribute of the image.
Examples
In the following examples, we shall consider loading the HTML file at path /tmp/selenium/index-30.html . The contents of this HTML file is given below.
<html>
<body>
<h3>Hello World</h3>
<img id="image1" src="/wp-content/uploads/2023/07/pe4-2.png" alt="My sample image 1">
<img id="image2" src="/wp-content/uploads/2023/06/If.png" alt="My sample image 2">
<img id="image3" src="/wp-content/uploads/2023/04/test_image-1.jpg" alt="My sample image 3" hidden>
</body>
</html>
1. Get the src of image whose id="image1"
In the following program, we initialize a driver object, load the specified URL, find the image element with id="image1", and get the value for src attribute of this image element.
The image with id="image1" is
<img id="image1" src="/wp-content/uploads/2023/07/pe4-2.png" alt="My sample image 1">
And the value of src attribute is /wp-content/uploads/2023/07/pe4-2.png.
Python Program
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
# Setup chrome driver
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()))
# Navigate to the url
driver.get('/tmp/selenium/index-30.html')
# Find the image
image = driver.find_element(By.ID, 'image1')
# Get src attribute
src = image.get_attribute('src')
print(src)
# Close the driver
driver.quit()
Output
https://pythonexamples.org/wp-content/uploads/2023/07/pe4-2.png
Summary
In this Python Selenium tutorial, we have seen how to get the value of src attribute of an image element in a webpage, with example programs.