2017-08-05 84 views
2

我使用Jsoup從網頁中提取鏈接,但我想避免img鏈接。 所以下面的代碼:Jsoup選擇他們的孩子不包含特定標籤的元素

Document doc = Jsoup.connect(i_Url).userAgent("chrome/5.0").get(); 
Elements links = doc.select("a[href]"); 

會讓我所有的鏈接,但他們中的一些圖片。執行以下操作:

links.stream().filter(link -> !link.tagName().equals("img")); 

不會起作用,因爲該元素的(=鏈接)孩子是一個與img標籤,例如:

<a href="index.htm" title="tutorialspoint"> 
    <img alt="tutorialspoint" src="/java/images/logo.png"> 
</a> 

我試過各種各樣的事情,如:

Elements links = doc.select("a[href]").select(":not(img)"); //or 
Elements links = doc.select("a[href]:not(img)"); //or 
Elements links = doc.select("a[href]") 
links.stream().filter(link -> link.children().contains(Tag.valueOf("img"))); 

我只是試圖玩各種變化,他們都沒有工作。談到HTML,我不是一個大專家。 幫助,將不勝感激。由於

回答

2

使用以下選擇:

a[href]:not(:has(img)) 

我剛纔用下面的單元測試測試它,就像一個魅力:

@Test 
public void testParsingLinksWithoutImagesInside() { 
    //given: 
    String html = "<a href=\"index.htm\" title=\"tutorialspoint\">\n" + 
      " <img alt=\"tutorialspoint\" src=\"/java/images/logo.png\">\n" + 
      "</a>"; 

    //when: 
    Document document = Jsoup.parse(html); 
    Elements elements = document.select("a[href]:not(:has(img))"); 

    //then: 
    assertThat(elements.size()).isEqualTo(0); 
} 

我希望它能幫助:)