gpt4 book ai didi

java - 如何使用 jsoup 从 html 元素获取字符串形式的 html 预览结果?

转载 作者:行者123 更新时间:2023-12-02 01:45:47 25 4
gpt4 key购买 nike

我想从 jsoup 元素获取 HTML 预览结果。假设我的 jsoup 元素具有以下 html 代码:

元素的 HTML 代码:

<div class="code-container">
<div id="highlighter_245626" class="syntaxhighlighter nogutter night">
<table border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="code">
<div class="container">
<div class="line number1 index0 alt2"><code class="comments">// C++ program for implementation of FCFS </code></div>
<div class="line number2 index1 alt1"><code class="comments">// scheduling </code></div>
<div class="line number3 index2 alt2"><code class="preprocessor">#include&lt;bits/stdc++.h&gt; </code></div>
<div class="line number4 index3 alt1"><code class="keyword bold">using</code> <code class="keyword bold">namespace</code> <code class="plain">std; </code></div>
</div>
</td>
</tr>
</tbody>
</table>
</div></div>

HTML 预览结果字符串:

// C++ program for implementation of FCFS
#include<bits/stdc++.h>
using namespace std;

我尝试使用 Element.Text() 获取 HTML 预览字符串,但遇到以下问题:

  • 断行结尾
  • 不规则间距

是否有更好的方法使用 jsoup 从 HTML 元素获取 HTML 预览结果作为字符串?

最佳答案

这将为您保留换行符:

public static String cleanPreserveLineBreaks(String bodyHtml) {

// get pretty printed html with preserved br and p tags
String prettyPrintedBodyFragment = Jsoup.clean(bodyHtml, "", Whitelist.none().addTags("br", "p"), new OutputSettings().prettyPrint(true));
// get plain text with preserved line breaks by disabled prettyPrint
return Jsoup.clean(prettyPrintedBodyFragment, "", Whitelist.none(), new OutputSettings().prettyPrint(false));
}

关于java - 如何使用 jsoup 从 html 元素获取字符串形式的 html 预览结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53686906/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com