I have a button, clicking on it generates a number which is wrapped in paragraph text such as <p>random number <p> , I want to get that random number value and do operations based on number it generates.

From below I need to get 34,756 number and store it in Java.

Here is the HTML code for it:

<div class="form-group">
<div class="alert alert-count">
<!-- react-text: 531 -->
<!-- /react-text -->
<!-- react-text: 532 -->
<!-- /react-text -->

And the XPath I used is as below:

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getText();

But on console it gives error as:

Exception in thread "main" java.lang.NullPointerException


Your example code is missing a " and a ) in the By.xpath. Guess you would get a syntaxError so your real code might be correct.

Do you wait for the element, because I think the findElement returns no object ( e.g. NULL) when it is not displayed (yet) and called getText() on a NULL is not possible , resulting in the NullPointerException. Read: https://stackoverflow.com/questions/20903231/how-to-wait-until-an-element-is-present-in-selenium

Keep in mind findElement does not wait for the element, it just fails instantly.


I think the there is a problem with the provided XPath, you are navigating to the paragraph tag (<p> tag) and fetching the text, I suggest you navigate to the bold tag (<b>tag) and fetch the respective value, like the following:

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p/b")).getText();
  • I think this should work – Sagar007 May 2 '17 at 9:00
  • Are you sure? In the C# bindings, the Text property gets ALL innerHTML, even from child nodes. – FDM May 2 '17 at 9:51
  • @FDM What you have said is also true. As Neils, Mentioned the syntax error may also be the case – the_coder May 3 '17 at 3:42

We are providing test automation services to clients and we have tried the below code for getting text of HTML tag:-

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getAttribute("innerhtml");          //getting text from HTML
    System.out.println(count);              //printing the text

you can get the text for an HTML tag using the below snippet

String count = driver.findElement(By.xpath("//div[@class='alert alert-count']/p).getAttribute("innerhtml");


It will fetch the text inside the HTML and prints it to console.

protected by Bharat Mane Dec 26 '17 at 11:07

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.