Extract Tags from a html file using Jsoup

2019-03-02 16:38发布

I am doing a structural analysis on web documents. For this i need to extract only the structure of a web document(only the tags). I found a html parser for java called Jsoup. But I don't know how to use it to extract tags.

Example:

<html>
 <head>
    this is head
 </head>
 <body>
    this is body
 </body>
</html>

Output:

html,head,head,body,body,html

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-03-02 17:15

Sound like a depth-first traversal:

public class JsoupDepthFirst {

    private static String htmlTags(Document doc) {
        StringBuilder sb = new StringBuilder();
        htmlTags(doc.children(), sb);
        return sb.toString();
    }

    private static void htmlTags(Elements elements, StringBuilder sb) {
        for(Element el:elements) {
            if(sb.length() > 0){
                sb.append(",");
            }
            sb.append(el.nodeName());
            htmlTags(el.children(), sb);
            sb.append(",").append(el.nodeName());
        }
    }

    public static void main(String... args){
        String s = "<html><head>this is head </head><body>this is body</body></html>";
        Document doc = Jsoup.parse(s);
        System.out.println(htmlTags(doc));
    }
}

another solution is to use jsoup NodeVisitor as follows:

   SecondSolution ss = new SecondSolution();
   doc.traverse(ss);
   System.out.println(ss.sb.toString());

class:

  public static class SecondSolution implements NodeVisitor {

        StringBuilder sb = new StringBuilder();

        @Override
        public void head(Node node, int depth) {
            if (node instanceof Element && !(node instanceof Document)) {
                if (sb.length() > 0) {
                    sb.append(",");
                }
                sb.append(node.nodeName());
            }
        }

        @Override
        public void tail(Node node, int depth) {
            if (node instanceof Element && !(node instanceof Document)) {
                sb.append(",").append(node.nodeName());
            }
        }
    }
查看更多
登录 后发表回答