How to get a single text node in Selenium WebDrive

2020-02-15 03:27发布

问题:

This question already has answers here:
Closed 2 years ago.

I want to get the text from a tag but without the text from nested tags. I.e. in the example below, I only want to get the string 183591 from inside the <small> tag and exclude the text Service Request ID: from the <span> tag. This is not trivial because the <span> tag is nested in the <small> tag. Is this possible with WebDriver and XPath?

The text in the tag is going to change every time.

<div id="claimInfoBox" style="background-color: transparent;">
<div class="col-md-3 rhtCol">
<div class="cib h530 cntborder">
<h4 class="no-margin-bottom">
<p>
<small style="background-color: transparent;">
<span class="text-primary" style="background-color: transparent;">Service Request ID:</span>
183591
</small>
</p>
<div class="border-bottom" style="background-color: transparent;"></div>
<div id="CIB_PersonalInfo_DisplayMode" class="cib_block">
<div id="CIB_PersonalInfo_EditMode" class="cib_block" style="display: none">
</div>
</div>
<script type="text/javascript">
</div>
</div>

回答1:

You are going to have to use String manipulation. Something like:

// you will need to adjust these XPaths to suit your needs
String outside = driver.findElement(By.xpath("//small")).getText();
String inside = driver.findElement(By.xpath("//span")).getText();

String edge = outside.replace(inside, "");


回答2:

The simplest way I've found is by getting the parent small node and the child span node and removing the number of characters in the child from the text of the parent:

public String getTextNode() {
  WebElement parent = driver.findElement(By.xpath("//small")); //or By.tagName("small")
  WebElement child = parent.findElement(By.xpath(".//span")); //or By.tagName("span")
  return parent.getText().substring(child.getText().length()).trim();
}


回答3:

The actual simplest way is using javascript executor as below:

JavascriptExecutor js = ((JavascriptExecutor)driver);
js.executeScript("return $(\"small\").clone().children().remove().end().text();");

This will return the text associated with the parent element 'small' only. Use trim() to omit leading and trailing whitespace. For the full explanation of what is happening here, please refer the link below.

Reference: http://exploreselenium.com/selenium/exclude-text-content-of-child-elements-of-the-parent-element-in-selenium-webdriver/