Search code examples
seleniumselenium-webdriverxpathautomation

Why doesn't my XPath expression return any results?


I have the following html:

<html>
  <body>
    <table>
      <tr>
      <tr>
      <tr>
      <tr>
      <tr>
        <td>Color Digest </td>
        <td>AgArAQICGQMVBBwTIRQHIwg0GUMURAZTBWQJcwV0AoEDAQ </td>
      </tr>
      <tr>
        <td>Color Digest </td>
        <td>2,43,2,25,21,28,0,0,0,0,0,0,0,0,0,0,0,0,0,0,33,7,0,0,0,0,0,0,0,0,0,0,0,0,0,0,8,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,25,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, </td>
      </tr>
    </table>
  </body>
</html>

and the following xpath:

tr[td='Color Digest']/td

and I'm getting zero results. Can someone explain why?

enter image description here


Solution

  • Inside xPath expression we can use attribute name and tag name(when it has text) as well. Here both <tr> and <td> are tag names. The valid xPath expressions be like,

    //tagname[@attributeName='value']
    

    and

    //tagname[@tagname='text']
    

    Inside td there is only text available so you need to write xPath like

    //td[text()='Color Digest ']
    

    or

    //tr[td='Color Digest ']
    

    If you need to use specific element then please use the match number like below,

    (//td[text()='Color Digest '])[1]
    

    or

    (//tr[td='Color Digest '])[1]
    

    Why it showed 0 matches for your xPath?

    You haven't given space at end of Digest.

    Yours:

    //tr[td='Color Digest']/td
    

    Corrected one:

    //tr[td='Color Digest ']/td