How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium selenium selenium

How to retrieve the value of the attribute aria-label from element found using xpath as per the html using Selenium


aria-label is attribute of span element, not button.You can get it like this:

btn = drive.find_element(By.xpath, "xpath") aria_label = btn.find_element_by_css_selector('span').get_attribute("aria-label")

Or if your goal is to find button with span contains attribute aria-label="Unlike":

btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"]]')#you can add class to xpath also if you needbtn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"] and contains(@class,"coreSpriteHeartOpen)]')


Following worked for me in Java,

WebElement btnelement= driver.findElement(                        By.xpath("//span[@aria-label='Unlike']"));System.out.println("Attribute value is " + btnelement.getAttribute("value"));


As per your question and the HTML you have shared it seems that the element is a React element, so to retrieve the attribute aria-label you have to induve WebDriverWait for the desired element to be visible and you can use the following solution:

print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "element_xpath_you_found"))).get_attribute("aria-label"))

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support import expected_conditions as EC