简体   繁体   English

使用Jsoup选择没有类的HTML元素

[英]Use Jsoup to select an HTML element with no class

Consider an html document like this one 考虑这样的一个html文档

 <div> <p>...</p> <p>...</p> ... <p class="random_class_name">...</p> ... </div> 

How could we select all of the p elements, but excluding the p element with random_class_name class? 我们如何选择所有p元素,但不使用random_class_name class排除p元素呢?

Elements ps = body.select("p:not(.random_class_name)");

You can use the pseudo selector :not 您可以使用伪选择器:not

If the class name is not known, you still can use a similar expression: 如果类名未知,您仍然可以使用类似的表达式:

Elements ps = body.select("p:not([class])");

In the second example I use the attribute selector [] , in the first the normal syntax for classes. 在第二个示例中,我使用属性选择器[] ,在第一个示例中,使用类的常规语法。

See the Jsoup docu about css selectors 请参阅有关CSS选择器Jsoup文档

Document doc = Jsoup.parse(htmlValue);
    Elements pElements = doc.select("p");         
    for (Element element : pElements) {
        String class = element.attr("class");
        if(class == null){
            //.....
        }else{
             //.....
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM