Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 721
ben Avatar asked Dec 23 '22 04:12

ben


1 Answers

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)]')
like image 170
Sers Avatar answered Dec 28 '22 11:12

Sers