2013-02-25 204 views
0

我使用JSOUP過濾鏈接出html身體。Jsoup選擇沒有標籤的鏈接

我用這些選擇:

Elements links = doc.select("a[href]"); // Select all links 
links.select("a[href*=#]").remove(); // remove links containing # 

但仍有連接包含一個主題標籤。這怎麼可能?

+0

當你說「還有鏈接」時,你的意思是在元素(這是一個列表本身)還是在文檔(doc)對象中? – 2013-02-25 21:20:08

+0

在我的元素集合中有鏈接包含「#」 – pila 2013-02-25 21:24:48

回答

4

Elements上的remove()方法不會從元素本身刪除匹配項,而是從關聯的Document對象中刪除匹配項。

例如,如果您有:

<html> 
<body> 
    <a href="#someid"></a> 
    <a href="http://www.google.pt"></a> 
</body> 
</html> 

links.select("a[href*=#]").remove();後,你會:

<html> 
<head></head> 
<body> 
    <a href="http://www.google.pt"></a> 
</body> 
</html> 

如果您想選擇所有非主題標籤的鏈接,你可以這樣做:

Elements links = doc.select("a[href~=[^#]*"); 
+0

另一種方式將是: Document doc = Jsoup.parse(html); doc.select(「a [href * =#]」)。remove(); \t \t \t元素鏈接= doc.select(「a [href]」); – pila 2013-02-28 19:46:18