2

I have a section of code like this:

<div id='wrapper'>
  <span>*</span>    
  Question 1
</div>

I want to store the Question 1 as a string in Java so when I use the xpath //div/text() to get the text "Question 1." However when I try to print the value, I am getting the error Invalid Selector Exception Xpath //div/text() is: [object Text]. It should be an element.

String text = driver.findElement(By.xpath("//div")).getText();

//returns *Question 1

String text = driver.findElement(By.xpath("//div/text()")).getText();

//returns error

How am I supposed to store just the Question 1. I can replace the * once I get it using the first method above but I don't want to do that.

williamtell
  • 301
  • 5
  • 17

1 Answers1

1

I'm not sure I know the best way to do this but this is a way. The issue is that you are looking for specific text within a group of elements that are children of the wrapper DIV. The only thing I can see in the example that you provided is that the text you want is outside of a containing tag. We can use that to our advantage. Basically the approach is to grab the entirety of the text inside wrapper and then loop through all child elements of wrapper removing the text contained within each from the original string. That should leave the text that you want. I have tested the code below using the example you provided.

String wrapperText = driver.findElement(By.id("wrapper")).getText().trim(); // get all the text under wrapper
List<WebElement> children = driver.findElements(By.cssSelector("#wrapper > *")); // get all the child elements of wrapper
for (WebElement child : children)
{
    String subText = child.getText(); // get the text from the child element
    wrapperText = wrapperText.replace(subText, "").trim(); // remove the child text from the wrapper text
}
System.out.println(wrapperText);
JeffC
  • 22,180
  • 5
  • 32
  • 55
  • Thank you for the reply but I am trying to find the answer to my specific question. Your method gets all the child objects and then filters out the text but I want to save a text node that I got from the xpath and then use it as a String. I am just being bugged by this unique problem. – williamtell Mar 18 '16 at 16:26
  • This is the only way to do this... see http://stackoverflow.com/questions/8505375/getting-text-from-a-node/8506502#8506502 – JeffC Mar 23 '16 at 18:39