繁体   English   中英

JSoup从标签内部解析数据

[英]JSoup parsing data from within a tag

我正在解析我需要的大多数数据,除了其中一个数据,因为它包含在href标记中,并且我需要显示在“ mmsi =“之后的数字

<a href="/showship.php?mmsi=235083844">Sunsail 4013</a>

我当前的解析器获取我需要的所有其他数据,并且在下面。 我尝试了一些操作,注释掉的代码偶尔返回未指定的条目。 有什么方法可以添加到下面的代码中,以便在返回数据时,在名称“ Sunsail 4013”之前返回数字“ 235083844”?

try {
        File input = new File("shipMove.txt");
        Document doc = Jsoup.parse(input, null);
        Elements tables = doc.select("table.shipInfo");
        for( Element element : tables )
        {
            Elements tdTags = element.select("td");
            //Elements mmsi = element.select("a[href*=/showship.php?mmsi=]");
            // 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());
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

此处已解析数据和html文件的示例

  1. 您可以在Element对象上使用attr来检索特定属性的值
  2. 如果字符串模式一致,请使用substring获取所需的值

// Using just your anchor html tag
String html = "<a href=\"/showship.php?mmsi=235083844\">Sunsail 4013</a>";
Document doc = Jsoup.parse(html);

// Just selecting the anchor tag, for your implementation use a generic one
Element link = doc.select("a").first();

// Get the attribute value
String url = link.attr("href");

// Check for nulls here and take the substring from '=' onwards
String id = url.substring(url.indexOf('=') + 1);
System.out.println(id + " "+ link.text());

给人,

235083844 Sunsail 4013

代码中for循环中的修改条件:

...
    for (Element td : tdTags) {
                // Print it's text if not empty
                final String text = td.text();
                if (text.isEmpty() == false) {
                    if (td.getElementsByTag("a").first() != null) {
                        // Get the attribute value
                        String url = td.getElementsByTag("a").first().attr("href");

                        // Check for nulls here and take the substring from '=' onwards
                        String id = url.substring(url.indexOf('=') + 1);
                        System.out.println(id + " "+ td.text());
                    }
                    else {
                        System.out.println(td.text());
                    }
                }
            }
...

上面的代码将打印所需的输出。

如果需要属性值,则应使用attr()方法。

for( Element td : tdTags ){
    Elements aList = td.select("a");
    for(Element a : aList){
        String val = a.attr("href");
        if(StringUrils.isNotBlank(val)){
            String yourId = val.substring(val.indexOf("=") + 1);


        }
}

暂无
暂无

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

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