简体   繁体   English

在Java中使用HTMLParser获取所有节点

[英]Get all nodes with HTMLParser in java

I need to get all the elements of an HTML file, because I have to represent them on a tree. 我需要获取HTML文件的所有元素,因为我必须在树上表示它们。 The problem is that I only can obtain the first node, the html node. 问题是我只能获得第一个节点,即html节点。

I am programming in Java with the HTMLParser Libraries. 我正在使用HTMLParser库在Java中进行编程。

My code is: 我的代码是:

import org.htmlparser.Node;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;

class Principal
{
    public static void main (String[] args) {
        try {
            Parser parser = new Parser("http://www.marca.com");
            NodeList list = parser.parse(null);
            for (int i = 0; i < list.size(); i++) {
                Node node = list.elementAt(i);
                System.out.println(node.getText());
            }
        } catch (ParserException pe) {
            pe.printStackTrace ();
        }
    }
}

I tryed with an iterator, but the result was the same. 我尝试使用迭代器,但是结果是相同的。

The execution of the code produces the following result: 代码的执行产生以下结果:

!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"


html xmlns="http://www.w3.org/1999/xhtml"

Does anyone know how I can get all the elements of the HTML file? 有谁知道我如何获得HTML文件的所有元素?

A Tree has different levels. 一棵树有不同的层次。 On your approch you are just selecting the nodes in the top level. 在您的方法中,您只是选择顶级节点。 In order to print all nodes you need to go all the childnodes. 为了打印所有节点,您需要转到所有子节点。

I think you shoud using jsoup Example: 我认为您应该使用jsoup示例:

Document doc = Jsoup.connect("http://www.marca.com").get();
Elements allNodes = doc.getAllElements()

You can reference here: http://jsoup.org/ 您可以在这里参考: http : //jsoup.org/

Trying differents methods I solve the problem with a recursive call to iterate the different chilren of the tree. 尝试不同的方法,我通过递归调用来迭代树的不同孩子,从而解决了这个问题。

Thanks for your help 谢谢你的帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM