6

I have an html table. I need to get the text of a td element with selenium.

Html structure:

<table id="myTable">
    <tbody>
     <tr>
      <td>
       <b>Success: </b>
       You have transferred 1,000.00 USD to DIST2. Your balance is now 19,979,000.00 USD.  ref: 2017011806292760301000301
      </td>
     </tr>
     </tbody>
    </table>

I tried using driver.findElement(By.xpath("//table[@id='myTable']/tbody/tr/td")).getText();

It is returning blank string. I need to get "You have transferred 1,000.00 USD to DIST2. Your balance is now 19,979,000.00 USD. ref: 2017011806292760301000301" from it. I think the td element contains a tag that is why it is not returning the value.

Is there any way to fetch the value?

Guy
  • 46,488
  • 10
  • 44
  • 88
Prasanta Biswas
  • 761
  • 2
  • 14
  • 26

3 Answers3

5

Your locator is correct. Try getAttribute("innerHTML") instead of getText()

driver.findElement(By.xpath("//table[@id='myTable']/tbody/tr/td")).getAttribute("innerHTML");
Guy
  • 46,488
  • 10
  • 44
  • 88
4

Use the following xpath (java code) -

String result = driver.findElement(By.xpath(".//*[@id='myTable']//td[contains(.,'You have transferred')]")).getText();
NarendraR
  • 7,577
  • 10
  • 44
  • 82
  • It is returning the whole text of the outer div. But worked with the String result = driver.findElement(By.xpath(".//*[@id='myTable']//td[contains(text(),'You have transferred')]")).getText(); – Prasanta Biswas Jan 18 '17 at 08:15
  • It says `Failed: By.xpath(...).getText is not a function` Please help – Paritosh M Feb 25 '21 at 02:39
0

HTML table is given and you need to get td text from the table.

URL for dummy HTML table : "https://www.cricbuzz.com/cricket-series/3130/indian-premier-league-2020/points-table"

If you need to fetch the text of first column (i.e Teams name) following is the code:

  List<String> ls = new ArrayList<String>();
   List<WebElement> rowSize= 
   driver.findElements(By.xpath("//td[@class='cb-srs-pnts- 
   name']"));

   for (int i = 0; i < rowSize.size(); i++) {
        ls.add(rowSize.get(i).getText());
        System.out.println(rowSize.get(i).getText());
    }  

ArrayList is used for adding all text to the list.

Suman
  • 529
  • 2
  • 5
  • 20