0

I am trying to extract the text "2000" and store this in a string from below HTML:

<table class="table" _ngcontent-c13="">
    <tbody _ngcontent-c13="">
        <tr _ngcontent-c13="">
            <th _ngcontent-c13="" scope="row">Amount</th>
            <td class="" _ngcontent-c13="">
                <b _ngcontent-c13="">$2000</b>
            </td>  <!-- Added by edit -->
        </tr>      <!-- Added by edit -->
    </tbody>       <!-- Added by edit -->
</table>           <!-- Added by edit -->

I am trying below XPath, but it's returning null:

String text= driver.findelement(by.xpath("xpath="//table[@class='table']/tbody/tr[1]/td")).getAttribute("value")
JeffC
  • 22,180
  • 5
  • 32
  • 55
M G
  • 19
  • 2
  • That code doesn't return null, it won't even compile. Please take a minute to update your question with the actual code you are using. – JeffC Sep 06 '18 at 23:32

3 Answers3

1

First of all you need to getText(), not attribute. Second, you need text of <b element, not <td. You also don't need xpath= in xpath Finally, XPath could be improved:

  • eliminated elements you don't care about (such as tbody)
  • don't use indexes like tr[1], they make xpath easily breakable. Instead use some meaningful locators. In this particular case looks like you want to find <td, whose <th says Amount.

So something like this:

String text= driver
    .findElement(
        By.xpath("//table[@class='table']//th[text()='Amount']/../td/b"))
    .getText();
timbre timbre
  • 12,648
  • 10
  • 46
  • 77
1

To match only the text "$2000" you can use this XPath expression:

//table[@class='table']/tbody/tr[1]/td/b

And to remove the "$", or the first char, use this XPath expression:

substring(//table[@class='table']/tbody/tr[1]/td/b,2)

To get these values, don't use .getAttribute("value"), because the values are no attributes. Try .getText() instead. (I also removed the typo of By and findElement):

String text= driver.findElement(By.xpath("substring(//table[@class='table']/tbody/tr[1]/td/b,2)")).getText();
zx485
  • 28,498
  • 28
  • 50
  • 59
0

Did you try adding the <b> element to the xpath? In addition, getAttribute() gets the attribute in the HTML tag, not the value inside the tag. You need the getText() function. Refer to this thread: Difference b/w getText() and getAttribute() in Selenium WebDriver?

TL;DR: Try this:

String text = driver.findelement(by.xpath("xpath="//table[@class='table']/tbody/tr[1]/td/b")).getText()

That should return $2000, and you can strip the $ easily.