如何找到不在<a> tag using HtmlCleaner?</a>内的节点元素

时间:2011-07-20 09:49:18

标签: java data-mining 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 anor find a. 由于Apple Online StoreApple Retail Storereseller是标记内的文字,因此,我想忽略这些字词。谢谢。

1 个答案:

答案 0 :(得分: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());
      }
    }