![](/img/trans.png)
[英]Copy All Elements inside the Node but not the node tag in XML using java
[英]How to find the node elements which is not inside the <a> tag using HtmlCleaner?
我使用 HTMLCleaner 來挖掘數據......這是它的工作原理:
HtmlCleaner cleaner = new HtmlCleaner();
final String siteUrl = "http://www.apple.com/";
TagNode node = cleaner.clean(new URL(siteUrl));
TagNode[] aTagNode = node.getAllElements(true);
for(int i = 0; i< aTagNode.length; i++){
if(!aTagNode[i].hasAttribute("a")){
System.out.println(aTagNode[i].getText());
}
}
但是我發現有一些問題......例如,獲取文本:
<a href="/choose-your-country/">
<img src="http://images.apple.com/home/elements/worldwide_us.png" alt="United States of America" height="22" width="22" />
<span class="more">Choose your country or region</span>
</a>
“選擇您的國家或地區”在 span 標簽內,但它的父節點是一個“a”標簽......我也不想要它,我只想要這樣的東西......:
<p class="left">Shop the <a href="/store/">Apple Online Store</a> (1-800-MY-APPLE), visit an <a href="/retail/">Apple Retail Store</a>, or find a <a href="/buy/">reseller</a>.</p>
我想要的結果是Stop the
, (1-800-MY-APPLE),visit an
, or find a
, and .
因為Apple Online Store
、 Apple Retail Store
和reseller
是 a 標簽里面的文字,所以,我想忽略這些文字。 謝謝你。
TagNode[] aTagNode = node.getAllElements(true);
ArrayList<TagNode> tagNodes = new ArrayList<TagNode>();
Set<TagNode> toBeRemoved = new HashSet<TagNode>();
for(int i = 0; i< aTagNode.length; i++){
if(!aTagNode[i].hasAttribute("a")){
tagNodes.add(aTagNode[i]);
}else{
TagNode[] children = aTagNode[i].getChildTags().
for(TagNode child : children) {
toBeRemoved.add(child);
}
}
}
for(TagNode node : tagNodes){
if(!toBeRemoved.contains(node)){
System.out.println(node.getText());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.