jsoup:如何选择具有满足条件的子节点的父节点

10

这是HTML的一部分(针对问题进行了简化):

<a href="/auctions?id=4672" class="auction sec"> 
 <div class="progress"> 
  <div class="guarantee"> 
   <img src="/img/ico/2.png" /> 
  </div> 
 </div> </a>
<a href="/auctions?id=4670" class="auction">  
 <div class="progress"> 
  <div class="guarantee"> 
   <img src="/img/ico/1.png" /> 
  </div> 
 </div> </a>
我想要得到一个向量,其中包含展示2.png图片的拍卖品的id(在本例中为id = 4672)。如何构造选择器查询以获取此信息? http://jsoup.org/apidocs/org/jsoup/select/Selector.html - 在这里我只能找到如何选择子级,而不能选择父级...
任何帮助都会被赞赏,包括使用其他库。我尝试了Jsoup,因为它似乎是最流行的。
1个回答

21

你可以使用parent()方法:

final String html = "<a href=\"/auctions?id=4672\" class=\"auction sec\"> \n"
        + " <div class=\"progress\"> \n"
        + "  <div class=\"guarantee\"> \n"
        + "   <img src=\"/img/ico/2.png\" /> \n"
        + "  </div> \n"
        + " </div> </a>\n"
        + "<a href=\"/auctions?id=4670\" class=\"auction\">  \n"
        + " <div class=\"progress\"> \n"
        + "  <div class=\"guarantee\"> \n"
        + "   <img src=\"/img/ico/1.png\" /> \n"
        + "  </div> \n"
        + " </div> </a>";

Document doc = Jsoup.parse(html);

for( Element element : doc.select("img") ) // Select all 'img' tags
{
    Element divGuarantee = element.parent(); // Get parent element of 'img'
    Element divProgress = divGuarantee.parent(); // Get parent of parent etc.

    // ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接