Search code examples
pythonseleniumxpathcss-selectorsgetattribute

Selenium Python get_attribute("src") returns None, eventhough there is a "src" attribute


Selenium Python get_attribute("src") returns None, eventhough there is a "src" attribute

Code Trials:

link = f"https://duckduckgo.com/?q={searchtext}&iax=images&ia=images"
driver = webdriver.Firefox()
driver.get(link)
time.sleep(2)
tabbutton = driver.find_element(By.CSS_SELECTOR, "div.tile:nth-child(3)")
webdriver.ActionChains(driver).click(tabbutton).perform()
imagelink = driver.find_element(By.CSS_SELECTOR, "div.detail__pane:nth-child(2) > div:nth-child(1) > div:nth-child(1) > div:nth-child(1) > a:nth-child(1) > img:nth-child(3)")
src = imagelink.get_attribute("src")
print(src)

It always prints "None" and every other attribute is working. The html is:

<img style="width: 218.333px; height: 262px; display: block;" alt="Flower Blume Pflanze Lila Gelb - ZoPix.NET" class="detail__media__img-highres  js-detail-img  js-detail-img-high" src="//external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fen.zopix.net%2Fimage_upload%2F138342-flower-blume-pflanze-lila.JPG&amp;f=1&amp;nofb=1">

Solution

  • To print the value of the src attribute you need 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.detail__media__img-highres[alt^='Flower Blume Pflanze Lila Gelb - ZoPix']"))).get_attribute("src"))
      
    • Using XPATH:

      print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//img[@class='detail__media__img-highres  js-detail-img  js-detail-img-high' and @alt='Flower Blume Pflanze Lila Gelb - ZoPix.NET']"))).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