【问题标题】:Java Jsoup - Element isn't removed from ElementsJava Jsoup - 未从元素中删除元素
【发布时间】:2015-02-04 19:12:04
【问题描述】:

我将从头开始,有这样的模式的html:

<div id="post_message_(some numeric id)">
    <div style="some style things">
        <div class="smallfont" style="some style">useless text</div>
        <table cellpading="6" cellspaceing=.......> a lot of text inside i dont need</table>
    </div>
    Text i need
</div>

那些带有样式的 div 和那个表格是可选的,有时只有

<div id="post">
     Text i need
</div>

我想将该文本解析为字符串。这是我正在使用的代码

Elements divsInside = element.getElementById("post_message_" + id).getElementsByTag("div");
    for(Element div : divsInside) {
        if(div != null && div.attr("style").equals("margin:20px; margin-top:5px; ")) {
            System.out.println(div.html());
            div.remove();
            System.out.println("div removed");
        }
    }

我添加了这些打印行以检查它是否找到它们,是的,它确实找到了正确的,但后来当我将其解析为字符串时:

String message = Jsoup.parse(divsInside.html().replaceAll("(?i)<br[^>]*>", "br2n")).text()
            .replaceAll("br2n", "\n");

由于某些原因,字符串再次包含所有已删除的内容。

我尝试通过迭代器删除它们,或者通过索引填充和删除元素,但结果是一样的。

【问题讨论】:

    标签: java jsoup


    【解决方案1】:

    所以你想得到Text i need。使用ElementownText()方法,其中Gets the text owned by this element only; does not get the combined text of all children

     private static void test(String htmlFile) {
        File input = null;
        Document doc = null;
        Element specificIdDiv = null;
    
        try {
            input = new File(htmlFile);
            doc = Jsoup.parse(input, "ASCII", "");
            doc.outputSettings().charset("ASCII");
            doc.outputSettings().escapeMode(EscapeMode.base);
    
            /** Get Element id = post_message_1 **/
            specificIdDiv = doc.getElementById("post_message_1");
    
            if (specificIdDiv != null ) {
                System.out.println("content: " + specificIdDiv.ownText());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • 顺便说一句,是否可以像这样提取换行符/
    • 提取
      ,你的意思是删除
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2020-10-25
    • 1970-01-01
    • 2015-07-29
    相关资源
    最近更新 更多