NewToJS
NewToJS

Reputation: 2101

Selenium: How do I check the src attribute of an image?

I'm trying to check the value of the src attribute for this image (highlighted in blue):

enter image description here

This is what I'm trying (not working):

visual = col_12_wrapper.find_element_by_class_name('visual')
left_text_img = visual.find_element_by_css_selector('div.col-sm-6:first-of-type')
left_img = left_text_img.find_element_by_tag_name('img')

#this line below fails
left_img[contains(@src,'../../static/images/databytes/colors/frame-0164.jpg')]

Upvotes: 1

Views: 1543

Answers (3)

PixelEinstein
PixelEinstein

Reputation: 1723

This line:

left_img[contains(@src,'../../static/images/databytes/colors/frame-0164.jpg')]

Is trying to use an XPATH as an index.

you would need to use find_element like so:

left_img.find_element_by_xpath(".//*[contains(@src, '../../static/images/databytes/colors/frame-0164.jpg')]")

I would recommend a more direct path of finding this element though:

direct_path = driver.find_element_by_xpath(".//div[@class='visual']/div[@class='col-sm-6']//img[@class='color-frame' and contains(@src, 'frame-0164.jpg')]")

If you want to get the element and then check it's src attribute, try this:

direct_path = driver.find_element_by_xpath(".//div[@class='visual']/div[@class='col-sm-6']//img[@class='color-frame']")
src_attribute = direct_path.get_attribute('src')

SIDENOTE: Based on your error message in the comments, you are running on an old chromedriver 2.35 which does not support your current version of Chrome 67, please go HERE to update your chromedriver as well. Recommended for build 67 is current chromedriver 2.40.

Upvotes: 1

Purendra Agrawal
Purendra Agrawal

Reputation: 558

Below is the XPath of the img element

//img[@class='color-frame'][contains(@src,'frame-0164.jpg')]

Upvotes: 0

cruisepandey
cruisepandey

Reputation: 29362

You can try with this code : [you can get the src attribute from the DOM like this and it's always good to use WebDriverWait]

img = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, 'div.color-squares.squares-20+img')))  
source = img.get_attribute("src")  
print(source)  

Note that you will have to import these :

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC  

In case you are looking for xpath , that would be :

//div[contains(@class,'color-squares squares-20')]/following-sibling::img

Upvotes: 0

Related Questions