您需要使用 JavaScript 来执行此操作。如果您的 webDriver(如 Firefox、Chrome 等)支持,您可以这样做:
public class Main
{
//@formatter:off
final static String JS_SCRIPT_GET_TEXT = "var element = arguments[0]; " +
"var text = ''; " +
"for (var i = 0; i < element.childNodes.length; i++) " +
" if (element.childNodes[i].nodeType === Node.TEXT_NODE) " +
" { " +
" text += element.childNodes[i].textContent + ' '; " +
" } " +
"return text; ";
//@formatter:on
public static void main(final String[] args)
{
final FirefoxDriver driver = new FirefoxDriver();
driver.get("http://en.wikipedia.org/wiki/HTML");
final List<WebElement> findElementsByCssSelector = driver.findElementsByCssSelector("#mw-content-text div");
final WebElement webElement = findElementsByCssSelector.get(0);
final String extractInnerText = extractInnerText(webElement, driver);
System.out.println("---------------------");
System.out.println("Seleniums .getText():\n" + webElement.getText());
System.out.println("\n\n---------------------");
System.out.println("Just the node text:\n" + extractInnerText);
}
public static String extractInnerText(final WebElement webElement, final WebDriver webDriver)
{
final JavascriptExecutor javascriptExecutor = (JavascriptExecutor) webDriver;
String webElementText = (String) javascriptExecutor.executeScript(JS_SCRIPT_GET_TEXT, webElement);
webElementText = webElementText.trim();
return webElementText;
}
}
对于此示例 Html:
<div class="dablink">
For the use of HTML on Wikipedia, see
<a href="/wiki/Help:HTML_in_wikitext" title="Help:HTML in wikitext">Help:HTML in wikitext</a>
.
</div>
它会打印你:
---------------------
Seleniums .getText():
For the use of HTML on Wikipedia, see Help:HTML in wikitext.
---------------------
Just the node text:
For the use of HTML on Wikipedia, see .
我认为这就是你所需要的。您可以将该extractInnerText(..)
方法应用于每个 web 元素。