Trouble generating the right Xpath

Viewed 59

My requirement is when I click on Facebook it should open the Facebook homepage. The xpath which I generated is //*[@class='sub2']/tbody/tr[2]/td/a but still it is giving me NoSuchElementException. Please help me out in generating the correct xPath.

<div> 
<center>
<table width="100%" class="sub2" style="float: none" border='8' 
cellspacing="8" cellpadding="8">
<tbody>
          <tr>
             <th>
               <center>Sample Program</center>
            </th>
         </tr>
         <tr>
         <td>
            <a href="https://facebook.com">
            <center> Facebook </center>
            </a>
         </td>
         </tr>
          <tr> </tr>
       </tbody>
  </table>
</center>

4 Answers

You can fetch the element by using the xpath:

//a[@href='https://facebook.com']

It seems that you have messed up absolute xpath with relative xpath. if you start by using // it means you are using relative xpath. // means it can search the element anywhere at the webpage. Since you are trying to find a tag with the text 'Facebook' you can try //a[contains(text(),"Facebook")] which means select an anchor tag within the whole DOM which contains the text "Facebook".

Or you can try //*[contains(text(),"Facebook")] if you are quite sure there are no other elements containing the text 'Facebook', since the above xpath means "select all elemnts in the DOM where it contains the text 'Facebook' ".

Related