2011-07-20 26 views
0

我用HTMLCleaner挖掘數據.... 這裏是它如何工作的:如何使用HtmlCleaner查找不在<a>標記內的節點元素?

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 anor find a. 因爲Apple Online StoreApple Retail Storereseller是一個標籤中的文本,所以,我想忽略這些話。謝謝。

回答

0
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()); 
     } 
    } 
相關問題