Home > Software design >  Find element by inner element text using selenium
Find element by inner element text using selenium

Time:08-11

I want to click an element by the text of a span who is the child of the element. How do I do this?

<button type="button"  tabindex="0"><span >OK</span><ion-ripple-effect  role="presentation"></ion-ripple-effect></button>

This is what I have tried but it didn't work.

@FindBy(css = "button[span:contains('OK')]")

CodePudding user response:

CSS Selectors with Selenium do not support locating elements by their text content. Only XPath supports that.
Try this XPath:

//button//span[text()='OK']

or

//button//span[contains(.,'OK')]

or

//button//span[contains(text(),'OK')]

So the element could be defined as following

@FindBy(xpath= "//button//span[text()='OK']")

Or

@FindBy(xpath= "//button//span[contains(.,'OK')]")

CodePudding user response:

Selenium doesn't supports the :contains pseudo-class anymore as @jari.bakken in their comment confirms:

AFAICT, the :contains pseudo-class isn't in the CSS spec and is not supported by either Firefox or Chrome (even outside WebDriver).

Further @dawagner in their comment also mentions:

contains isn't a valid CSS3 selector; because of this several browsers don't natively support contains, so Selenium (and WebDriver) don't claim to support it._


Solution

However you can still use the other attributes to construct a CssSelector to identify the element as follows:

@FindBy(css = "button.alert-button.ion-focusable.ion-activatable.sc-ion-alert-md span.alert-button-inner.sc-ion-alert-md")

As an alternative you can also use either of the following Xpath based locator strategies:

@FindBy(xpath = "//button[@class='alert-button ion-focusable ion-activatable sc-ion-alert-md']//span[@class='alert-button-inner sc-ion-alert-md']")

Using the innerText:

@FindBy(xpath = "//button[@class='alert-button ion-focusable ion-activatable sc-ion-alert-md']//span[@class='alert-button-inner sc-ion-alert-md' and text()='OK']")

or even:

@FindBy(xpath = "//span[@class='alert-button-inner sc-ion-alert-md' and text()='OK']")

even possibly:

@FindBy(xpath = "//span[text()='OK']")
  • Related