0

我有一个包含以下 html 代码的网页:

....
<div class="some_class">Text I want 
   <span class="another_class">Text I don't want</span>
   ....more junk...
   ....a lot more junk....
</div>

我尝试调用 getText(),它为我提供了 div 中的所有文本,其中包含许多我不想要的其他文本。我的问题是:我怎样才能只得到我想要的文本而不求助于某种解析或提取子字符串等?

谢谢!

4

1 回答 1

0

您需要使用 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 元素。

于 2013-09-08T16:25:01.333 回答