Search code examples
pythonhtmlseleniumtextjupyter-lab

Interacting with HTML element by text in Selenium Python


I need to interact with an HTML element with an id such as

<span class="a-button-inner">
    <input name="submit.addToCart" aria-label="Aggiungi al carrello dal venditore VERONCART SRL con prezzo 775,00&nbsp;€
" aria-labelledby="" class="a-button-input" type="submit">
<span id="a-autoid-2-offer-1-announce" class="a-button-text" aria-hidden="true"> Aggiungi al carrello </span>
</span>

I have many of this buttons on the site and I must identify them by the numerical text inside the aria label,in this case 775.I have tried
with

wd.find_element_by_xpath('//*[contains(text()='775')]')

and

wd.find_element_by_css_selector('//input[value*='775']')

None of them works. I've been stuck on this for days, I'd be grateful I someone could help me.


Solution

  • You are not far from the solution. To specify the selector in which attribute we want to do the search of the value, instead of using text() which mean the text of the input, we use the attribute name, which is @aria-label.

    wd.find_element_by_xpath("//input[contains(@aria-label, '775')]")
    

    Please note to not excluding the 775 to our XPath.