在 jsoup 中选择正确的选择器

Choosing the right selectors in jsoup

我是 jsoup 的新手,我很难理解我应该为以下内容选择哪些选择器 html:

<div class="details">
<div></div>
<div></div>
<div></div>
<div>
     <b>
        Title :
    </b>
     dog
</div>
</div>

我需要对许多 html 页面执行此操作,并且每个页面都有不同的标题值(例如狗、猫等)。那么,如果我想让我的 java 代码只得到 "dog" 这个词,我该怎么办?可能采用这种格式:

Elements links = doc.select(???);

我只需要知道在“???”中输入什么地方。

如果您只需要从每个页面 select 一个实例,以下解决方案将起作用:

// select the first child of a div with class="details" that has a <b> tag child
Element titleDiv = doc.select("div.details div:has(b)").first();

// print out the text owned by the div (e.g. the animal's name)
System.out.println(titleDiv.ownText()); 

如果您需要在单个页面上 select 此元素的多个实例,以下方法也适用:

// select all divs that have <b> and are children of div.details
Elements titleDivs = divs.select("div.details div:has(b)");

for (Element div : titleDivs) {

    // call ownText to get the animal name
    System.out.println(div.ownText());
}

对于您的示例 HTML,两者都将打印:

dog