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

ben picture ben · Aug 24, 2018 · Viewed 12.8k times · Source

I have the following HTML span:

<button class="coreSpriteHeartOpen oF4XW dCJp8">
    <span class="glyphsSpriteHeart__filled__24__red_5 u-__7" aria-label="Unlike"></span>
</button>

I also have a webElement representing the button containing this span that I have found using xpath. How can I retrieve the aria-label value (Unlike) from the element?

I tried to do:

btn = drive.find_element(By.xpath, "xpath") 
btn.get_attribute("aria-label")

but it returns nothing. How to retrieve the text value of an element with 'aria-label' attribute from the element object?

Answer

Sers picture Sers · Aug 24, 2018

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 need
btn = drive.find_element(By.XPATH, '//button[./span[@aria-label="Unlike"] and contains(@class,"coreSpriteHeartOpen)]')