alekslkta
alekslkta

Reputation: 79

Selenium Webdriver (Java) - exclude a particular tag from the css selector

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?

Upvotes: 1

Views: 2182

Answers (3)

Mahantesh Hallur
Mahantesh Hallur

Reputation: 1

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

Upvotes: 0

Alpha
Alpha

Reputation: 14086

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];

Upvotes: 0

alecxe
alecxe

Reputation: 474231

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, '');

Upvotes: 1

Related Questions