Use Jsoup to select an HTML element with no class

半世苍凉 提交于 2019-12-07 05:08:05

问题


Consider an html document like this one

<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?


回答1:


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

You can use the pseudo selector :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




回答2:


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


来源:https://stackoverflow.com/questions/31440864/use-jsoup-to-select-an-html-element-with-no-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!