1

How can I exclude a tag from the css selector. I have a html code below:

<div class="info">
    <h3>Test 1</h3>
    John Smith
</div>

I need to getText() only for John Smith not for <h3>.

The statement below is return full text Test 1 John Smith:

String txtFix = new WebDriverWait(Login.driver, 100).until(ExpectedConditions.visibilityOfElementLocated
                (By.cssSelector(".info"))).getText();

Is it possible to get somehow only John Smith using css selector?

3 Answers 3

1

This is a "classic" problem with selenium since a CSS selector or xpath expression has to always refer to an actual element - you cannot directly get the text node.

What you can do here is to:

  • get the div element's text
  • get the h3 element's text
  • remove the h3 element's text from the div element's text

Implementation:

String div = new WebDriverWait(Login.driver, 100).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".info"))).getText();
String h3 = div.findElement(By.tagName('h3')).getText();
String txtFix = div.replace(h3, '');
Sign up to request clarification or add additional context in comments.

Comments

0

If you get text using following:

driver.findElement(By.cssSelector(".info")).getText();

it returns following:

Test 1
John Smith

If you see properly, after Test 1, char \n is introduced hence John Smith is on another line.

Hence, if you want to retrieve only John Smith, it can be achieved using split like following:

String text = driver.findElement(By.cssSelector(".info")).getText().split("\n")[1];

Comments

0
JavascriptExecutor jse = (JavascriptExecutor) driver;       
       if (jse instanceof WebDriver) {
           String text = jse.executeScript("document.getElementByClassName("info").nextSibling";");
           System.out.println(text);
       }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.