【问题标题】:Jsoup - <noscript> content in <head> gets interpreted as textJsoup - <head> 中的 <noscript> 内容被解释为文本
【发布时间】:2020-12-07 08:26:24
【问题描述】:

我遇到了一个问题,将以下 HTML 结果解析为不需要的结果。

HTML

<html>
<head>
<title>Try jsoup</title>
<noscript><p>thisisatest</p></noscript>
<noscript><img id="tracking-test-noscript" style="width: 1px; height: 1px" src="http://fullwithsheep/img/tracking3.jpg"></noscript>
</head>
<body>
<noscript><p>thisisatest</p></noscript>
<p>This is <a href="http://jsoup.org/">jsoup</a>.</p>
<noscript><img id="tracking-test-noscript" style="width: 1px; height: 1px" src="http://fullwithsheep/img/tracking3.jpg"></noscript>
</body>
</html>

JSOUP对Document的解释

<html>
<head>
<title>Try jsoup</title>
<noscript>&lt;p&gt;thisisatest</noscript>
<noscript>&lt;img  id="tracking-test-noscript" style="width: 1px; height: 1px" src="http://fullwithsheep/img/tracking3.jpg"&gt;</noscript>
</head>
<body>
<noscript><p>thisisatest</p></noscript>
<p>This is <a href="http://jsoup.org/">jsoup</a>.</p>
<noscript><img id="tracking-test-noscript" style="width: 1px; height: 1px" src="http://fullwithsheep/img/tracking3.jpg"></noscript>
</body></html>

您可以从头节点中的 noscript 标记中看到 innerHTML 被解释为文本 - 我想要的是 jsoup 仍然会将它们解释为 html 而不是文本(没有将 &lt; 等等)

我为解决此问题所做的解决方法是在中断 Jsoup.parse 后选择所有 noscript 标记,并尝试将相应 noscript 标记的文本转换回 html。但是,感觉这不是正确的方法 - 这是 Jsoup 库中的错误还是这种行为是故意的?

【问题讨论】:

标签: java html jsoup


【解决方案1】:

使用xmlParser 避免不必要的 HTML 修改:

Document doc = Jsoup.parse(html, "", Parser.xmlParser());

默认解析器treats input as HTML5, and enforces the creation of a normalised document, based on a knowledge of the semantics of the incoming tags
而 xmlParser assumes no knowledge of the incoming tags and does not treat it as HTML, rather creates a simple tree directly from the input 这正是你所需要的。

引用来自文档:https://jsoup.org/apidocs/org/jsoup/parser/Parser.html#xmlParser()

【讨论】:

  • 知道为什么相同的代码在头部和主体中的解释不同吗?特别是这一行:
猜你喜欢
  • 2015-12-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多