简体   繁体   中英

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?

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

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];
JavascriptExecutor jse = (JavascriptExecutor) driver;       
       if (jse instanceof WebDriver) {
           String text = jse.executeScript("document.getElementByClassName("info").nextSibling";");
           System.out.println(text);
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM