如何使用 JSOUP 获取多个项目

How to get multiple items with JSOUP

所以我有一个HTML的块我需要在这里解析:

<div class="item" style="width: 100%">
    <a href="example.com" class="sitelink"><img class="photo" src="placeholder_10.jpg" alt="Alt Text" title="title"></a>
    <div class="content">
        <h5><a href="example.com/moreinfo">title</a></h5>
        <p class="lifespan">More text 1<br> More text 2</p>
            <p>Some preview Text <a href="example.com/readmore" class="sitelink">Read More <span class="fa fa-angle-double-right"></span></a></p>
        </div>
    </div>

我需要从第 6 行中提取第 2、4、5 行和 link

但是页面上有多个这样的部分,我也需要得到。我不知道如何遍历每个部分并仅提取一个 div class 中的信息,然后继续下一个部分。

我已经尝试了一些东西,但是它们错得离谱,没有意义在这里张贴。我有的就在这里

Elements metaElems = doc.getElementsByClass("item");
for (Element metaElem : metaElems) {
    System.out.println(metaElem);
}

这样做我得到了所有 div class="item" 部分,而且只有那些部分。但我确信有一种比使用正则表达式解析每一行更简单的方法。

Elements items = doc.getElementsByAttributeValueMatching("class", "item")
for (Element item : items) {
    Element siteLink = item.getElementsByAttributeValueMatching("class", "sitelink")[0];
    //... and so on
}

这里有更多信息, https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#getElementsByAttributeValueMatching-java.lang.String-java.lang.String-

如果您喜欢使用 css 查询(如 injQuery),请尝试 doc.select

Elements items = doc.select("div.item")
for (Element item : items) {
    Element siteLink = item.select("a.sitelink")[0];
    //... and so on
}

https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#select-java.lang.String-