JSoup使用Java解析包含html表的文本文件

时间:2014-04-11 16:12:09

标签: java html jsoup

我真的不确定如何获取放入数据库所需的信息,下面的代码只打印整个文件。

File input = new File("shipMove.txt");
Document doc = Jsoup.parse(input, null);    
System.out.println(doc.toString());

我的HTML是第61行的here,我需要获取列标题下的项目,但也要获取不在列标题下但在href标记中的MMSI编号。除了从网页上获取HTML之外,我还没有使用过JSoup。我只能真正看到使用php的教程,而不是不使用它。

1 个答案:

答案 0 :(得分:0)

要获取这些信息,最好的方法是使用 Jsoup的选择器API 。使用选择器,您的代码看起来像这样(pseudeocode!):

File input = new File("shipMove.txt");
Document doc = Jsoup.parse(input, null);


Elements matches = doc.select("<your selector here>");

for( Element element : matches )
{
    // do something with found elements
}

这里提供了很好的文档:Use selector-syntax to find elements。如果您遇到困难,请描述您的问题。

以下是该选择器的一些提示,您可以使用:

// Select the table with class 'shipinfo'
Elements tables = doc.select("table.shipinfo");

// Iterate over all tables found (since it's only one, you can use first() instead
for( Element element : tables )
{
    // Select all 'td' tags of that table
    Elements tdTags = element.select("td"); 

    // Iterate over all 'td' tags found
    for( Element td : tdTags )
    {
        // Print it's text if not empty
        final String text = td.text();

        if( text.isEmpty() == false )
        {
            System.out.println(td.text());
        }
    }
}