【问题标题】:how can I make a filter with the content of a div using html parser in javajava - 如何在java中使用html解析器制作带有div内容的过滤器
【发布时间】:2023-04-09 01:36:02
【问题描述】:

我正在尝试使用 htmlparser 库解析 HTML 字符串。 html是这样的:

<body>
        <div class="Level1">
            <div class="row">
                <div class="txt">
                    Date of analysis:
                </div><div class="content">
                    02/03/11
                </div>
            </div>
        </div><div class="Level1">
            <div class="row">
                <div class="txt">
                    Site:
                </div><div class="content">
                    13.0E
                </div>
            </div>
        </div><div class="Level1">
            <div class="row">
                <div class="txt">
                    Network type:
                </div><div class="content">
                    DVB-S
                </div>
            </div>
        </div>
</body>

我需要为给定的“txt”提取“内容”信息。我制作了一个过滤器,它返回 class="level1" 的 div,但我不知道如何用 div 的内容制作过滤器,我的意思是如果 txt 的值为 Site: 然后读取 13.0 之类的内容E.

  NodeList nl = parser.extractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "Level1")));
       

有人可以帮我解决这个问题吗?如何在 div 中读取 div? 谢谢!!

【问题讨论】:

    标签: java html filter html-parsing


    【解决方案1】:
    NodeList nl = parser.extractAllNodesThatMatch(new AndFilter(new TagNameFilter("div"), new HasAttributeFilter("class", "Level1")));
    

    最好这样做:

    NodeList nl = parser.parse(null); // you can also filter here
    
    NodeList divs = nl.extractAllNodesThatMatch(
      new AndFilter(new TagNameFilter("DIV"), 
        new HasAttributeFilter("class", "txt")));
    
    if( divs.size() > 0 ) {
      Tag div = divs.elementAt(0);
      String text = div.getText(); // this is the text of the div
    }
    

    【讨论】:

    • nl.item(0)row 元素,我想我们想要类为 txt 的 div。
    • 我尝试了您的建议,但没有成功... :( 我达到的最大值是: Parser parser = Parser.createParser(htmlFile, null); NodeList nl = parser.extractAllNodesThatMatch(new AndFilter (new TagNameFilter("DIV"),new HasAttributeFilter("class", "txt"))); for(int i = 0; i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 2011-07-22
    相关资源
    最近更新 更多