【问题标题】:Use Jsoup to select an HTML element with no class使用 Jsoup 选择一个没有类的 HTML 元素
【发布时间】:2015-10-05 02:40:14
【问题描述】:

考虑一个像这样的 html 文档

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

我们如何选择所有p 元素,但不包括random_class_name 类的p 元素?

【问题讨论】:

    标签: java html css jsoup selector


    【解决方案1】:
    Elements ps = body.select("p:not(.random_class_name)");
    

    你可以使用伪选择器:not

    如果类名未知,你仍然可以使用类似的表达式:

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

    在第二个示例中,我使用属性选择器[],在第一个示例中使用的是类的正常语法。

    Jsoup docu about css selectors

    【讨论】:

    • 对不起,如果问题不清楚,“random_class_name”实际上是一个未知的类,而不是同名的类
    • 其他p没有课程?
    • 查看我的编辑。只要其他

      没有分配任何类,它就可以工作。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-08
      • 2019-09-09
      • 1970-01-01
      • 2011-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多