这是我要运行的代码:
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
不打印任何内容...我该怎么办?
最佳答案
问题是doc.getAllElements().first()
返回
<html>
<head></head>
<body>
<a href="/name/zola-1">ZOLA <span class="tiny">(1)</span></a>
</body>
</html>
当你期望的时候
<a href="/name/zola-1">ZOLA <span class="tiny">(1)</span></a>
以下应该为您工作:
String html = "<a href=\"/name/zola-1\">ZOLA <span class=\"tiny\">(1)</span></a>";
Document doc = Jsoup.parse(html);
Elements links = doc.getElementsByTag("a");
System.out.println(links.get(0));
System.out.println(links.get(0).ownText());
输出:
<a href="/name/zola-1">ZOLA <span class="tiny">(1)</span></a>
ZOLA