我正在解析我需要的大多数数据,除了其中一个数据,因为它包含在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文件的示例
attr
在Element
对象上使用来检索特定属性的值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());
}
}
}
...
上面的代码将打印所需的输出。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句