Prasanta Biswas
Prasanta Biswas

Reputation: 839

How to get text of td element using selenium?

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?

Upvotes: 7

Views: 41210

Answers (3)

Suman
Suman

Reputation: 619

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.

Upvotes: 0

NarendraR
NarendraR

Reputation: 7708

Use the following xpath (java code) -

String result = driver.findElement(By.xpath(".//*[@id='myTable']//td[contains(.,'You have transferred')]")).getText();

Upvotes: 4

Guy
Guy

Reputation: 50909

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

driver.findElement(By.xpath("//table[@id='myTable']/tbody/tr/td")).getAttribute("innerHTML");

Upvotes: 5

Related Questions