使用 Jsoup select 一个没有 class 的 HTML 元素
Use Jsoup to select an HTML element with no class
考虑像这样的 html 文档
<div>
<p>...</p>
<p>...</p>
...
<p class="random_class_name">...</p>
...
</div>
我们如何 select 所有 p
元素,但不包括具有 random_class_name
class 的 p
元素?
Elements ps = body.select("p:not(.random_class_name)");
你可以使用伪选择器:not
如果 class 名字不知道,你仍然可以使用类似的表达式:
Elements ps = body.select("p:not([class])");
在第二个示例中,我使用了属性选择器 []
,在第一个示例中,我使用了 classes.
的正常语法
Document doc = Jsoup.parse(htmlValue);
Elements pElements = doc.select("p");
for (Element element : pElements) {
String class = element.attr("class");
if(class == null){
//.....
}else{
//.....
}
}
考虑像这样的 html 文档
<div>
<p>...</p>
<p>...</p>
...
<p class="random_class_name">...</p>
...
</div>
我们如何 select 所有 p
元素,但不包括具有 random_class_name
class 的 p
元素?
Elements ps = body.select("p:not(.random_class_name)");
你可以使用伪选择器:not
如果 class 名字不知道,你仍然可以使用类似的表达式:
Elements ps = body.select("p:not([class])");
在第二个示例中,我使用了属性选择器 []
,在第一个示例中,我使用了 classes.
Document doc = Jsoup.parse(htmlValue);
Elements pElements = doc.select("p");
for (Element element : pElements) {
String class = element.attr("class");
if(class == null){
//.....
}else{
//.....
}
}