How to getAttribute("xpath")?

211 views
Skip to first unread message

PopVerifyPete

unread,
Feb 8, 2021, 6:14:50 PM2/8/21
to Selenium Users
(I am using TestNG/Selenium/Java/Eclipse)

The xpath I used is a simple one: 

WebElement BasicHTMLTable = driver.findElement(By.xpath("//table[@id='table2']"));

But at times could be more complex.  
How can I retrieve the exact xpath that I wrote in my code?

I tried using getAtribute as below with xpath, but that did not work:
String tableID = BasicHTMLTable.getAttribute("xpath");

I used .toSting, and that almost works, but gets additional text.  Not sure how it will work with more complex xpaths, and if it is only getting the path I used to create the webelement in my selenium code (which is what I want) or the xpath version in the DOM:
System.out.println(BasicHTMLTable.toString());


Originally, I wanted to create a method like this:

public string GetCellData (WebElement Table, iRow, iCol)
{
List<WebElement> objListTable = Table.findElements(By.xpath("/tbody/tr["+iRow +"]/td[" + iCol +"]"));
string cellData = objListTable.get(0).getText();  
return cellData ;
}


In my method above, thought I could use this to identify the table this part works):
WebElement BasicHTMLTable = driver.findElement(By.xpath("//table[@id='table2']")); 
and then append more to the xpath to drill into a specific cells of the table:
List<WebElement> objListTable = BasicHTMLTable.findElements(By.xpath("/tbody/tr[2]/td[2]"));
But the objListTable line above completely ignores the start of the xpath found in webelement BasicHTMLTable.
There are 2 tables in my web page, where I am trying to get data from the 2nd table (hence my xpath is using id=table2).
BasicHTMLTable does identify the 2nd table, but objListTable is Instead identifying the 1st table.  

So as a work around to the above method (and going back to my original question) I thought to do some more like this:
public string GetCellData (WebElement Table, iRow, iCol)
{
string TablePath = Table.getAttribute("xpath");
string cellData = Table.findElements(By.xpath(TablePath + "/tbody/tr["+iRow +"]/td[" + iCol +"]"));
return cellData ;
}

Or is there another way to do this?
Keep in mind that I want to use a methods where I do not have to hard code the xpath or other attributes of the WebTable element for each method (example: getcelldata, getrowcount, verifycell data...) I define.

Pete
Reply all
Reply to author
Forward
0 new messages