我是 Jsoup 新手,我正在尝试解析 html 文件以查找所有没有 id 的元素。到目前为止我只有这个代码片段:
Document doc = Jsoup.parse(input, null);
for (Element el : doc.getAllElements()) {
hasId = el.hasAttr("id");
if (!hasId) {
idList.add(el.tagName());
} else {
log.info("id:" + el.attr("id"));
}
}
正确找到带有 id 的元素。我的问题是我只想扫描有 id 的起始元素。我可以用 Jsoup 处理这个问题吗?
最佳答案
我不确定我是否正确理解你的问题,但我认为你只想选择所有没有 id
的元素属性。如果是这样,这应该有效:
doc.select("*:not([id])")
有一个full list of selectors在 jsoup 网站上。
更新:
这是一个完整的示例:
import org.jsoup.Jsoup;
import org.jsoup.nodes.*;
public class Soup {
public static void main(String[] args) {
String data = "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"> <tr> <td class=\"reportheader\" align=\"left\" nowrap width=\"720\">Outside my Dreams</td> </tr> </table>";
Document doc = Jsoup.parse(data);
StringBuilder tags = new StringBuilder();
for (Element el : doc.select("body *:not([id])")) {
tags.append(el.tagName());
tags.append(' ');
}
System.out.println(tags);
}
}
在我的机器上运行上述命令会得到以下输出: table tbody tr td
请注意,我稍微更改了查询:"body *:not([id])"
。添加body
前面不包括 <html><title></title><body> ... </body></html>
Jsoup 在解析 data
中的部分文档时自动添加字符串。
关于java - Jsoup:在html中查找没有id的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11966730/