0

I'm learning how to use selenium by using java. I got a problem. Having html code:

<h2 class="cart-popup-product__title">Laptop Dell XPS 13 2015 13.3inch Touch (Xám) - Hàng nhập khẩu</h2>

And this is my code to get text:

By productName = By.className("cart-popup-product__title");
public String ProductName(){
    String pn = driver.findElement(productName).getText();
    return pn;
}

Eclipse display error message: NullPointerException. I have tried to use xpath, cssSelector but it's not working.

*Update: I've solved my problem. I just add this.driver = driver; to constructor. I forgot to add when initialize constructor.

Thanks all for helping me improve.

Trai Nguyen
  • 9
  • 1
  • 1
  • 2

1 Answers1

-1

It can possible be an another element with the same class name without any text.

FindElement() method does not throw a NoSuchElementException - this is a clear sign that the element was found.

Is it possible to find element in browser console by the following locator? Also you can try to find desired element's parent and then call getText() method.

  • `WebElement` without text will give an empty `String`, not `null`. And even if it was null the OP doesn't do anything with it so it wont cause `NullPointerException`. – Guy Dec 08 '16 at 08:32
  • Thanks for your support. I've solved my prolem. Just add `this.driver = driver;` to constructor. – Trai Nguyen Dec 08 '16 at 15:11