jsoup - 使用 Jsoup 解析 HTML 以获取单个元素的文本
问题描述
我需要解析以下文本并为每个文本创建单独的对象。我尝试了几种方法来做到这一点,但它没有以我需要的格式提供结果。
正文是:
String text = "This is start of a text <a href=\"https://google.com/sample\">followed by a link sample</a>and ending with some text."
使用以下代码:
Document document = Jsoup.parse(text);
Elements elements = document.select("*");
for(Element e : elements){
System.out.println( e.tagName() + ": " + e.text());}
实际结果是
root: This is start of a text followed by a link sampleand ending with some text.
html: This is start of a text followed by a link sampleand ending with some text.
head:
body: This is start of a text followed by a link sampleand ending with some text.
p: This is start of a text followed by a link sampleand ending with some text.
a: followed by a link sample
我需要得到以下结果,以便我可以为每个文本创建一个自定义对象
body: This is start of a text
a:followed by a link sample
body:and ending with some text.
解决方案
为了避免返回所有孩子使用e.ownText()
的文本,但在这种情况下这还不够,因为你想要单独的This is start of a text
and and ending with some text.
,但ownText()
返回它加入了:This is start of a text and ending with some text.
。
要获取分隔文本的列表,请使用e.textNodes()
body 的输出:
body: [
This is start of a text , and ending with some text.]
a: [followed by a link sample]
另一个好处是你保持原创
。
此外,如果您不喜欢冗余html: []
并head: []
添加到您的文档中,您应该使用 XML 解析器:
Document document = Jsoup.parse(text, "", Parser.xmlParser());
要保持文本分隔和<a>
文本顺序,请尝试使用递归迭代:document.childNodes()
然后childNodes()
对每个节点进行迭代。您可以通过检查来识别文本节点if (node instanceof TextNode)
。
推荐阅读
- typescript - 如何在 TypeScript 的单个声明文件中增加多个模块?
- docker - 全新安装后无法连接到 Docker 守护进程
- python - 在相关矩阵的第一行创建条形图
- c# - 如何创建具有参数化构造函数的类的实例
- node.js - 将函数参数保存到从 node.js 中的 socket.on 传入的全局变量中
- android - Google Play 结算 > 在设备上验证购买 > 使用 ProGuard 进行混淆
- java - Java中的“如何使用自定义模式格式化LocalDate”
- python - 尝试安装 pip 时权限被拒绝 - [Errno 13] 权限被拒绝:'/Library/Python/2.7/site-packages/test-easy-install-60057.pth'
- python - 将 pandas df 转换为 parquet-file-bytes-object
- python - 错误:重复的外键约束名称