How to set xPath of Java Selenium when there are two table of same class

Viewed 339

I trying to test this WEBSITE table data by using Java Selenium but there are two tables on the webpage with same class name datatable. When I set as:

private final static String table   = "//table[contains(@class,'datatable')]"; 

then its scraping first table on the page and once its given both tables data of first page.

How can I set xPath separately for each table with one class on the same page?

2 Answers

You can use indexes like

private final static String tablefirst   = "(//table[contains(@class,'datatable')])[1]"; 
private final static String tablelast   = "(//table[contains(@class,'datatable')])[last()]"; 

You can use below xpath as well. more generic.

private final static String tablefirst   = "//p[text()='Found 1096 Airline Codes']/following::table[1]"; 
private final static String tablelast   = "//p[text()='Found 9130 Location Codes']/following::table[1]"; 

It is very easy if you know, and from your question I assume you know which is first and which is second table. In that case use:

driver.findelements(By.xpath("//table[contains(@class,'datatable')]")).get(index)

if you want first table

index=0

if you want secondtable

index=1
Related