發生錯誤的原因是手動生成的html的標簽沒有閉合或者語法不規范導致的,可以使用jsoup工具對html文件進行標准化處理,實現如下:
html 可以是富文本 或者是 html 文件
private static String formatHtml(String html) {
String contents = html.replaceAll("src=\"/cds_filestorage/download-s", "src=\"https://orangecds.com/cds_filestorage/download-s");
String contentss = contents.replaceAll("data-mce-src=\"/cds_filestorage/download-s", "data-mce-src=\"https://orangecds.com/cds_filestorage/download-s");
String contentRe = contentss.replaceAll("<video.*?>.+?</video>", "");
log.info("content2Html-轉換后的html:" + contentss);
org.jsoup.nodes.Document doc = Jsoup.parse(contentRe);
// jsoup生成閉合標簽
doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
System.out.println("----"+doc.html());
org.jsoup.nodes.Document doc = Jsoup.parse(contentRe);
// 去除過大的寬度
String style = doc.attr("style");
if ((!style.isEmpty()) && style.contains("width")) {
doc.attr("style", "");
}
Elements divs = doc.select("div");
for (Element div : divs) {
String divStyle = div.attr("style");
if ((!divStyle.isEmpty()) && divStyle.contains("width")) {
div.attr("style", "");
}
}
// jsoup生成閉合標簽
doc.outputSettings().syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
return doc.html();
}
輸入String類型的html文本對象,返回標准的html格式的String對象。
需要用到的jsoup包見我上傳的文件
原文鏈接:https://blog.csdn.net/lxh1205509119/article/details/110402366