【问题标题】:JSoup search by attribute and classJSoup 按属性和类搜索
【发布时间】:2016-09-17 21:16:10
【问题描述】:
你可以这样做:
Elements links = doc.select("a[href]");
查找所有带有 href 属性的“a”元素。
你可以这样做:
doc.getElementsByClass("title")
获取具有名为“title”的类的所有元素
但是我怎样才能做到这两点呢? (即搜索带有“href”标签的“a”元素,该标签也具有“title”类)。
【问题讨论】:
标签:
java
android
web-scraping
jsoup
【解决方案1】:
你可以简单地拥有
Elements links = doc.select("a[href].title");
这将选择所有具有href 属性和title 类的<a>。类通过by prepending it with a dot:
选择器组合
完整示例:
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>"
}