2013-04-25 125 views
7

后,我想提取使用jsoup每个标签后文本的文本。有没有办法直接选择它,或者我必须在整个事情上执行.substring?Jsoup选择标签

<div> 
<a href="#"> I don't want this text </a> 
**I want to retrieve this text** 
</div> 

回答

22
public static void main(String... args) throws IOException { 

    Document document = Jsoup.parse("<div>" 
      + "<a href=\"#\"> I don't want this text </a>" 
      + "**I want to retrieve this text**" + "</div>"); 

    Element a = document.select("a").first(); 

    Node node = a.nextSibling(); 
    System.out.println(node.toString()); 
} 

输出

**I want to retrieve this text** 
+0

谢谢。正是我需要的。 – Mintz 2013-04-25 16:12:06

+0

非常好,谢谢! – Dax 2014-09-13 07:16:00

0

当然可以。

  1. 得到<div>第一的HTML,然后使用.html()
  2. 得到<a>元素选择它的HTML,并把它的HTML
  3. 得到<a>元素的HTML的长度
  4. 排除的第一部分。
0

我认为上面的答案缺乏普遍性,尽管提供了一个解决方向。

nextSibling()是unuseble而HTML结构改变。

当我提到Jsoup API时,我找到了一个名为textNodes()的方法,它可以从这个元素中获取文本节点列表。

public static String getTextAfterTag(Element ele) { 
    String text = ""; 
    for(TextNode node: ele.textNodes()) { 
    text += node.text(); 
    } 
    return text; 
} 

希望能提供帮助。