Search code examples
seleniumselenium-webdriverxpathwebdriverxpath-1.0

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.


Solution

  • 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.