首页 > 解决方案 > 使用 Jsoup 非递归提取文本

问题描述

这是我要运行的代码:

String html = "<a href=\"/name/zola-1\">ZOLA <span class=\"tiny\">(1)</span></a>";

Document doc = Jsoup.parse(html); //connect  to the page
Element element = doc.getAllElements().first(); //recive the names elements

System.out.println(element.text()); //prints "ZOLA (1)"
System.out.println(element.ownText()); // prints nothing

我的目标是只提取“ZOLA”,没有子节点的文本,但ownText什么也不打印……我该怎么做?

标签: javahtmljsoup

解决方案


你可以使用这个:

String html = "<a href=\"/name/zola-1\">ZOLA <span class=\"tiny\">(1)</span></a>";
Document doc = Jsoup.parse(html);
Element elementA =  doc.selectFirst("a");
System.out.println(elementA.ownText()); // ZOLA

推荐阅读