简体   繁体   English

JSoup按属性和类搜索

[英]JSoup search by attribute and class

You can do: 你可以做:

Elements links = doc.select("a[href]");

to find all "a" elements with an href attribute. 查找具有href属性的所有“ a”元素。

And you can do: 您可以执行以下操作:

doc.getElementsByClass("title")

to get all elements with a class that is called "title" 使用名为“ title”的类获取所有元素

But how can I do both? 但是我该怎么办? (Ie search for an "a" element with an "href" tag that also has the class "title"). (即,搜索带有“ href”标签且也具有“ title”类的“ a”元素)。

You can simply have 你可以简单地拥有

Elements links = doc.select("a[href].title");

This will select all <a> having an href attribute with a title class. 这将选择所有具有href属性和title类的<a> The class is passed by prepending it with a dot : 通过在类前面加一个点来传递该类:

Selector combinations 选择器组合

  • Any combination, eg a[href].highlight 任何组合,例如a[href].highlight

Full example: 完整示例:

public static void main(String[] args) {
    Document doc = Jsoup.parse(""
            + "<div>"
            + "  <a href='link1' class='title another'>Link 1</a>"
            + "  <a href='link2' class='another'>Link 2</a>"
            + "  <a href='link3'>Link 3</a>"
            + "</div>");

    Elements links = doc.select("a[href].title");
    System.out.println(links); // prints "<a href="link1" class="title another">Link 1</a>"
}

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

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