Hesoti
Hesoti

Reputation: 87

XPath using classname and contains text

I was looking for an answer to how to find an element that has a class and contains text.

I've got two answers.

For me, only 2nd answer worked. Can anyone pls explain the difference for 'contains text' part.? As both answers don't mention it.

Upvotes: 2

Views: 11187

Answers (2)

Alferd Nobel
Alferd Nobel

Reputation: 3949

In my case the html looked like this :

<ki5-tab text="Super Boal" ki5-tab="" slot="default-1" selected="true"></ki5-tab>

xpath :

//ki5-tabcontainer/ki5-tab[contains(@text,'Boal')]

Upvotes: 1

undetected Selenium
undetected Selenium

Reputation: 193088

For a demonstration consider the following HTML:

<div class="credit_summary_item">Professor</div>

There is:

  • Only one value of the class attribute i.e. credit_summary_item.
  • And the innerText i.e. Professor contains no leading and trailing spaces.

So, to locate this element you can use either of the following solutions:

  • Using text():

    //div[@class='credit_summary_item' and text()='Professor']
    
  • Using contains():

    //div[@class='credit_summary_item' and contains(., 'Professor')]
    

This usecase

But in your usecase it seems contains(@class, 'credit_summary_item') worked which implies the element have multiple classes. So apart from credit_summary_item there are some other values present as class attributes.

Upvotes: 9

Related Questions