如何在JSoup Java中仅显示HTML标签?

3

我正在做一个学校项目,尝试解析HTML网页以仅显示标签,就像下面的输出一样,不带闭合标签。(我手动编写)

<html>
 <head> 
  <title>
  <basefont> 
 <body> 
  <h1>
  <h2>

这是我目前仅在主方法中的代码。

public class ReadWithScanner {
public static void main(String[] args) throws IOException 
{
    String URL ="http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html";
    Document doc = Jsoup.connect(URL).get();        
    //Element p = doc.select("p");
    //Elements p = doc.getElementsByTag("h6");
    Elements p = doc.select("html");
    //System.out.println(p);

     DoublyLinkedList theList = new DoublyLinkedList();

      theList.insert(p);      // insert at front

      theList.displayTree();
}

这是我的输出结果的几行代码。

在此输入图片描述


问题是什么? - Alkis Kalogeris
如何在JSoup Java中仅显示HTML标记? - Onlytito
1个回答

3
package Scrapper;

import java.util.LinkedList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.jsoup.select.NodeVisitor;

class TagVisitor implements NodeVisitor {

    public static class TagInfo {

        public String name;
        public int depth;

        TagInfo(String name, int depth) {
            this.depth = depth;
            this.name = name;
        }
    }

    private LinkedList<TagInfo> tags = new LinkedList<>();

    public void head(Node node, int depth) {
        String tag = node.nodeName();
        if(!tag.startsWith("#")) {
            tags.add(new TagInfo('<'+node.nodeName()+'>', depth)); 
        }
    }

    public void tail(Node node, int depth) {
        //Do nothing
    }

    public LinkedList<TagInfo> getTags() {
        return tags;
    }

    public void printTree() {
        for(TagInfo info : tags) {
            String indentation = new String(new char[info.depth*2]).replace('\0', ' ');
            System.out.println(indentation + info.name);
        }
    }
}

public class MainJsoup {

    public static void main(String[] args) throws Exception {

        //InputStream stream = new FileInputStream("test.html");
        //Document doc = Jsoup.parse(stream, "UTF-8", "");
        String URL ="http://csb.stanford.edu/class/public/pages/sykes_webdesign/05_simple.html";
        Document doc = Jsoup
                        .connect(URL)
                        .userAgent("Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201")
                        .timeout(2000)
                        .get();     
        TagVisitor visitor = new TagVisitor();
        doc.traverse(visitor);
        visitor.printTree();
    }
}

1
没问题。玩得开心。 - Alkis Kalogeris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接