![](/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.