如何使用<a>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> 

"Choose your country or region"位于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.因为Apple Online Store, Apple Retail Storereseller是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());
      }
    }

相关内容

  • 没有找到相关文章

最新更新