Home > Back-end >  How to get the text from element in Selenium
How to get the text from element in Selenium

Time:08-04

I am trying to fetch the text ($315.50) from:

<td id="balance" >$315.50</td>

I am not succeeding though, I have tried:

@FindBy(how = How.CSS, using = "#balance")
private WebElement balance;

and

@FindBy(how = How.ID, using = "#balance")
private WebElement balance;

With these selectors I than do:

System.out.println("Balance"   balance)

as result I get

Balance[[ChromeDriver: chrome on WINDOWS (4ccbccdb5b54de0526e0ec68db88a48c)] -> css selector: #balance]

Or if try to do something else with it, I get errors saying that the methods receives an empty string.

For other elements in my test framework I can do manage to fetch the text from elements. The general setup does not seem to be the problem. Anyone an idea what I am doing wrong in this specific example?

CodePudding user response:

Considering the HTML:

<td id="balance" >$315.50</td>

To identify the element you can use either of the following locator strategies:

  • Using id:

    @FindBy(how = How.ID, using = "balance")
    private WebElement balance;
    
  • Using cssSelector:

    @FindBy(how = How.CSS, using = "td#balance")
    private WebElement balance;
    
  • Using xpath:

    @FindBy(how = How.XPATH, using = "//td[@id='balance']")
    private WebElement balance;
    

To print the text:

  • Using getText():

    System.out.println(balance.getText())
    
  • Using getAttribute("innerHTML"):

    System.out.println(balance.getAttribute("innerHTML"))
    
  • Using getAttribute("innerText"):

    System.out.println(balance.getAttribute("innerText"))
    
  • Using getAttribute("textContent"):

    System.out.println(balance.getAttribute("textContent"))
    
  • Related