alekslkta alekslkta - 1 year ago 195
Java Question

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

I need to
only for John Smith not for

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

String txtFix = new WebDriverWait(Login.driver, 100).until(ExpectedConditions.visibilityOfElementLocated

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

Answer Source

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


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, '');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download