Select link in a table with jsoup using Java code
Select link in a table with jsoup using Java code
我需要在 table:
下载 link
<table cellpadding="0" cellspacing="3" border="0">
<tr>
<td><img class="img" src="...path" /></td>
<td><a href="the file I want to download">File</a> -
<a id="1569" class="tepLink" href="javascript:void(0);">[Click me]</a>
</td>
</tr>
</table>
这是我尝试过的:
Element table = doc.select("table[cellpadding=\"0\" cellspacing=\"3\" border=\"0\"]").first();
Element dwlLink = table.select("td:has(a)").first();
String absPath = dwlLink.attr("abs:href");
//use download manager to download from string absPath
我总是得到一个 "null object reference" 所以我一定是那个代码错了,它应该怎么办?
只是 select 所有锚标记,然后获取 Elements 对象中的第一个元素。
Elements anchorTags = doc.select("table[cellpadding=0][cellspacing=3][border=0] a");
if(anchorTags.isEmpty())
{
System.out.println("Not found");
}
else
{
System.out.println(anchorTags.first());
}
编辑:
我更改了 select 方法以包含 cellpadding、cellspacing 和 border 属性,因为这看起来就像您在其中一个示例中所追求的那样。
此外,如果元素列表为空,Element.first() 方法 returns 为 null。调用该方法时始终检查 null 以防止 NullPointerExceptions。
table.select("td:has(a)").first();
将 select 第一个包含锚点的 <tr>
元素。它不会 select 锚点 <a>
本身。
您可以执行以下操作:
Element aEl = doc.select("table[cellpadding] td a").first();
我需要在 table:
下载 link<table cellpadding="0" cellspacing="3" border="0">
<tr>
<td><img class="img" src="...path" /></td>
<td><a href="the file I want to download">File</a> -
<a id="1569" class="tepLink" href="javascript:void(0);">[Click me]</a>
</td>
</tr>
</table>
这是我尝试过的:
Element table = doc.select("table[cellpadding=\"0\" cellspacing=\"3\" border=\"0\"]").first();
Element dwlLink = table.select("td:has(a)").first();
String absPath = dwlLink.attr("abs:href");
//use download manager to download from string absPath
我总是得到一个 "null object reference" 所以我一定是那个代码错了,它应该怎么办?
只是 select 所有锚标记,然后获取 Elements 对象中的第一个元素。
Elements anchorTags = doc.select("table[cellpadding=0][cellspacing=3][border=0] a");
if(anchorTags.isEmpty())
{
System.out.println("Not found");
}
else
{
System.out.println(anchorTags.first());
}
编辑:
我更改了 select 方法以包含 cellpadding、cellspacing 和 border 属性,因为这看起来就像您在其中一个示例中所追求的那样。
此外,如果元素列表为空,Element.first() 方法 returns 为 null。调用该方法时始终检查 null 以防止 NullPointerExceptions。
table.select("td:has(a)").first();
将 select 第一个包含锚点的 <tr>
元素。它不会 select 锚点 <a>
本身。
您可以执行以下操作:
Element aEl = doc.select("table[cellpadding] td a").first();