0

Using Selenium/Java, I have a table where I need to find the country Austria, and then determine which Company is in that country. I found the xPath:

//td[.='Austria']

to Austria in the table, but is there a better way to use cells then move two cells to the left to find the Company name (Ernest Handel? Is there a better solution?

The table is at: https://www.w3schools.com/html/html_tables.asp

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Lorena
  • 19
  • 1

2 Answers2

0

To print the Company i.e. Ernst Handel associated with the country Austria you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

  • Using xpath and preceding:

    driver.get("https://www.w3schools.com/html/html_tables.asp");
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    System.out.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td[.='Austria']//preceding::td[2]"))).getText());
    driver.quit();
    
  • Using xpath and preceding-sibling:

    driver.get("https://www.w3schools.com/html/html_tables.asp");
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    System.out.println(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//td[.='Austria']//preceding-sibling::td[2]"))).getText());
    driver.quit();
    
  • Console Output:

    Ernst Handel
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

Another XPath strategy is to select the first cell from the row whose third cell is 'Austria' (assuming you know that column 3 contains country names and column 1 contains company names):

//tr[td[3]='Austria']/td[1]
Conal Tuohy
  • 2,561
  • 1
  • 8
  • 15