Animesh
Animesh

Reputation: 228

WebElement.findElement method is finding element under WebDriver scope

I have the following HTML code on which I am trying to run my selenium test

<html>

<head></head>

<body>
  <table id="Original">
    <tr>
      <td>Original-11</td>
      <td>Original-12</td>
      <td>Original-13</td>
    </tr>
    <tr>
      <td>Original-21</td>
      <td>Original-22</td>
      <td>Original-23</td>
    </tr>
    <tr>
      <td>Original-31</td>
      <td>Original-32</td>
      <td>Original-33</td>
    </tr>
  </table>

  <br/><br/>

  <table id="Duplicate">
    <tr>
      <td>Duplicate-11</td>
      <td>Duplicate-12</td>
      <td>Duplicate-13</td>
    </tr>
    <tr>
      <td>Duplicate-21</td>
      <td>Duplicate-22</td>
      <td>Duplicate-23</td>
    </tr>
    <tr>
      <td>Duplicate-31</td>
      <td>Duplicate-32</td>
      <td>Duplicate-33</td>
    </tr>
  </table>
</body>

</html>

The selenium java code looks like this:

public static void main(String[] args) throws Exception
    {
        System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/src/test/drivers/chromedriver.exe");

        WebDriver drv = new ChromeDriver();
        drv.get("C:/Users/MYUserName/git/er_test/SeleniumTestHtml.html");

        WebElement tableElement = drv.findElement(By.id("Duplicate"));
        WebElement rowElement = tableElement.findElement(By.xpath("//tr[2]"));
        WebElement cellElement = rowElement.findElement(By.xpath("//td[2]"));
        System.out.println(rowElement.getText());
        System.out.println(cellElement.getText());

        drv.close();
        drv.quit();

    }

I am expecting a result as follows :
Duplicate-21 Duplicate-22 Duplicate-23
Duplicate-22

But I am getting this result :
Original-21 Original-22 Original-23
Original-12

Am I doing something wrong here ?

Upvotes: 4

Views: 3254

Answers (1)

Tarun Lalwani
Tarun Lalwani

Reputation: 146630

Your problem is that // makes you go back to search from top root element.

Which means

WebElement rowElement = tableElement.findElement(By.xpath("//tr[2]"));

Is as good as

WebElement rowElement = driver.findElement(By.xpath("//tr[2]"));

If you need to search only inside the current element then you should use

WebElement rowElement = tableElement.findElement(By.xpath(".//tr[2]"));

Upvotes: 18

Related Questions