Skip to content Skip to sidebar Skip to footer

Extracting Text From Webtable Selenium Webdriver

HTML:

Solution 1:

According to provided HTML of table row, I'm not sure what could be unique locator. May be, below provided cssSelector would be unique here to extract the text :-

tr[valign = 'top'] > td > p[align = 'left']

You can use above cssSelector , if it is not unique you need to share more details about table HTML. So I could provide you unique locator.

Or if you want to locate this element with text, you can use below xpath which would be unique :-

.//td[contains(.,'itinerary has been booked')]

Solution 2:

many days ago, i faced this problem. It has two approach to solve this proble

  • using normailize-space of xpath. ẽample in my project, i have to get text in tr element with br tag String temp = td.findElement(By.xpath(".//span[normalize-space()]")).getText();
    • using javascript to get content with css selector. i used the first approach. Sorry if my english is not good

Solution 3:

Using Java, there is another generic way I usually prefer to use to read any given table data and the content in it

  HashMap<Integer, HashMap<String, String>> tableData = new HashMap<Integer, HashMap<String, String>>();
  HashMap<String, String> tableCellDataMap = null;
  WebElement table = driver.findElement(By.id("<table_id>"));

  /**
   *  Call this method to get Table Cell Data by passing WebElement table
   *  @Params table
   *  
   *  @author Fayaz
   **/publicstatic HashMap<String, String> getTableData(WebElement table) {
  List<WebElements> tableColHeaders = table.findElements(By.tagName("th"));
  List<WebElements> tableRows = table.findElements(By.tagName("tr"));

  // Start rowIndex with '1' because in the zeroth index we get 'th' tags   for(int rowIndex = 1; rowIndex < tableRows.size(); rowIndex++) {
     List<WebElement> tableCells = tableRows.get(rowIndex).findElements(By.tagName("td"));
     for(int cellIndex = 0; cellIndex < tableCells.size(); cellIndex++) {
         String tableCellData = tableCells.get(cellIndex).getText();
         String tableColName  = tableColHeaders.get(cellIndex).getText();
         tableCellDataMap     = new HashMap<String, String>();
         tableCellDataMap.put(tableColName, tableCellData);
     }
     tableData.put(rowIndex, tableCellDataMap);
  }
  return tableCellDataMap;
 }

Actually, it can even be further modularize to make Table utility with methods like, getTableHeader(), getRowSize(), getColSize(), getData(int rowIndex), getData(int colIndex)

Post a Comment for "Extracting Text From Webtable Selenium Webdriver"