1

I'm trying to get the src of an element as a string.

I used find_element_by_xpath() to find the element. I'm able to use element.get_attribute("class") to get the class but unable to get the src this way.

A snippet of my code:

image = driver.find_element_by_xpath('//*[@id="irc_cc"]/div[2]/div[1]/div[2]/div[1]/a/img')
print(image.get_attribute("class"))
print(image.get_attribute("src"))

Here is the result my terminal:

irc_mi None

This is what the element in chrome inspect element looks like:

element

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Charles Zhang
  • 109
  • 1
  • 12
  • I believe you might have more than one items matching with that xpath and the first matching item might not have the `src`. Can you quickly check `print(len(driver.find_elements_by_xpath('//*[@id="irc_cc"]/div[2]/div[1]/div[2]/div[1]/a/img')))` to make sure you have only one item with that matching xpath. – supputuri Jul 08 '19 at 04:27

1 Answers1

0

Seems you were close. To extract the src attribute as the element is JavaScript enabled element you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "img.irc_mi[alt='Image result for snowman']"))).get_attribute("src"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='irc_mi' and @alt='Image result for snowman']"))).get_attribute("src"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Using your method, I've ran into another problem. It possible to call EC.visibility_of_element_located without the @alt parameter? Can I get the src by just using the class name? – Charles Zhang Jul 08 '19 at 22:37
  • 1
    I just used the absolute xpath instead of "//img[@class='irc_mi' and @alt='Image result for snowman']" and it works now. Great! – Charles Zhang Jul 09 '19 at 04:40