2014-09-19 4 views
1

Je réalise une analyse structurelle sur des documents web. Pour cela je n'ai besoin d'extraire que la structure d'un document web (uniquement les tags). J'ai trouvé un analyseur html pour Java appelé Jsoup. Mais je ne sais pas comment l'utiliser pour extraire des tags.Extrait des balises d'un fichier html en utilisant Jsoup

Exemple:

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

sortie:

html,head,head,body,body,html 
+0

pour (élément el: doc.select ("*")) { \t System.out.println (el.nodeName()); } vous donnera déjà le résultat de l'analyse: html, head, body Si le document est bien formaté, il est clair que vous obtenez des paires de tags. –

Répondre

2

sonore comme une profondeur d'abord 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)); 
    } 
} 

une autre solution consiste à utiliser jsoup NodeVisitor comme suit:

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

Classe:

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()); 
      } 
     } 
    } 
+0

J'ai utilisé le second. Fonctionne bien !! merci @ user1121883 –

Questions connexes