【问题标题】:How to get Value in between a tag with HTMLParser如何使用 HTMLParser 在标签之间获取值
【发布时间】:2011-06-28 18:24:12
【问题描述】:

我正在使用 HTMLParser (org.htmlparser) 来解析 HTML。我已经用它来访问标签并获得像这样的标签属性:

NodeVisitor linkvisitor = new NodeVisitor() {
    public void visitTag(Tag tag) {
        if ("script".equalsIgnoreCase(name)) {
            String srcValue = tag.getAttribute("src");
            // do stuff 
        }
    }
        // How to get value instead of tag?     
}

但是现在我需要获取标签之间的值,比如<script> 标签?

提前致谢。

【问题讨论】:

  • 不是说htmlparser有什么问题,但是你考虑过JSoup吗?
  • @Andrew,感谢您的提示。刚到 JSoup 网站,看起来很有趣,我一定会研究一下。毕竟,我的代码设计非常松散耦合,我可以从解析器切换到解析器。再次感谢。

标签: java html html-parsing


【解决方案1】:

因为您已经知道Tag 是一个脚本标签,您应该能够将其转换为ScriptTag。然后你应该可以使用CompositeTag.getStringText()

NodeVisitor linkvisitor = new NodeVisitor() {
  public void visitTag(Tag tag) {
    if (tag.getTagName().equals("SCRIPT")) {
      ScriptTag script = (ScriptTag)tag;
      String srcValue = script.getAttribute("src");
      String text = script.getStringText();
    }
  }
};

有关设置visitTag 方法的说明,请参阅Javadocs for NodeVisitor

如果您只关心带有结束标签的标签,您可以查看它是否是CompositeTag 的实例,否则该标签没有结束标签(<tag/>)。然后调用我上面提到的getStringText()方法。

if(tag instanceof CompositeTag) {
  CompositeTag cTag = (CompositeTag)tag;
  String text = cTag.getStringText();
}

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多