Getting the middle column value with the other two column values using xpath in web table

Viewed 426

<tr>
    <td>Alfreds Futterkiste</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>

[https://www.w3schools.com/html/html_tables.asp]

you can find the sample web table in the link. I want contact value with the company and country.

I have tried something like this

//td[text()='Laughing Bacchus Winecellars']//following-sibling::td and //td[text()='Canada']//preceding-sibling::td
4 Answers

To extract the middle column value i.e. Maria Anders you need to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using the Company text Alfreds Futterkiste:

    • xpath:

      //table[@id='customers']//tr//td[text()='Alfreds Futterkiste']//following::td[1]
      
    • Line of code:

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@id='customers']//tr//td[text()='Alfreds Futterkiste']//following::td[1]"))).getText());
      
  • Using the Country text Germany:

    • xpath:

      //table[@id='customers']//tr//td[text()='Germany']//preceding::td[1]
      
    • Line of code:

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//table[@id='customers']//tr//td[text()='Germany']//preceding::td[1]"))).getText());
      

Try this one to select required td node:

//td[preceding-sibling::td[.="Alfreds Futterkiste"] and following-sibling::td[.="Germany"]]

Try following xpath:

//td[preceding-sibling::td[text()='Laughing Bacchus Winecellars'] and following-sibling::td[text()='Canada']]
Related