我需要获取此表中的下载链接:
<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
我总是得到一个“空对象引用”,所以我的代码一定是错误的,它应该做什么?
最佳答案
只需选择所有 anchor 标记,然后获取 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());
}
编辑:
我更改了选择方法以包含单元格填充、单元格间距和边框属性,因为这看起来就像您在示例之一中所追求的。
此外,如果 Elements 列表为空,则 Element.first() 方法将返回 null。调用该方法时始终检查 null 以防止 NullPointerExceptions。
关于java - 使用 Java 代码通过 jsoup 选择表中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34287037/