Getting the alt attribute value of an img tag using selenium

Question:

i’m very new to selenium and having a bit of trouble to extract the alt value from an img tag.
my html code :

<span class="logo">
<img src="url..........." alt="my logo">
</span>

python code : driver.find_element_by_class_name("logo").find_element_by_xpath("//img").get_attribute('alt'))

I also tried:

driver.find_element_by_class_name("logo").get_attribute('alt'))

and

driver.find_element_by_xpath("//span[@class='logo']//img").get_attribute('alt'))

and

span = driver.find_element_by_class_name("logo")
span.find_element_by_xpath("//img").get_attribute('alt')

I can print the objects but when i add the getAttribute() all of them return an empty string. Am i missing something? I tried to add alt = True in the find_element_by…..() method but it says unexpected argument! Can someone please explain what’s happening here.

Thanks in advance.

Asked By: muntasir adnan

||

Answers:

Possibly you have to wait until the element is fully loaded before getting it attributes.
Also, I can’t see any variable on the left side receiving the extracted attribute value in your code.
Try this:

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

wait = WebDriverWait(driver, 20)

alt_val = wait.until(EC.visibility_of_element_located((By.XPATH, "//span[@class='logo']//img"))).get_attribute('alt'))

print(alt_val)

UPD
As I understand from your updates you are trying to extract the alt from retailers logos on the dialog presented by clicking the "Retailers" button.
If so the code will be as following:

wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "span.retlogo img")))
images = driver.find_elements_by_css_selector("span.retlogo img")
for img in images:
    print(img.get_attribute('alt'))
Answered By: Prophet

The correct way to extract text is like this

driver.find_element("class name", "logo").find_element("tag name", "img").get_attribute("alt")
Answered By: Hell_ Raisin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.