朋友们,我必须解析URL中的描述,其中解析的内容有一些HTML标签,那么我该如何将其转换为纯文本。
朋友们,我必须解析URL中的描述,其中解析的内容有一些HTML标签,那么我该如何将其转换为纯文本。
是的,Jsoup将是更好的选择。只需按照以下步骤将整个HTML文本转换为纯文本。
String plainText= Jsoup.parse(yout_html_text).text();
Jsoup.parse(html).wholeText()
。 - sonrad10只是要去掉HTML标签很简单:
// replace all occurrences of one or more HTML tags with optional
// whitespace inbetween with a single space character
String strippedText = htmlText.replaceAll("(?s)<[^>]*>(\\s*<[^>]*>)*", " ");
但不幸的是,要求从来不会那么简单:
通常情况下,<p>
和<div>
元素需要分别处理。可能存在包含>
字符(例如javascript)的cdata块,这会破坏正则表达式等。
htmlString=htmlString.replaceAll("\\<.*?\\>", "");
<dependency>
<!-- jsoup HTML parser library @ https://jsoup.org/ -->
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
现在在你的Java代码中:
public static String html2text(String html) {
return Jsoup.parse(html).wholeText();
}
import net.htmlparser.jericho.*;
import java.util.*;
import java.io.*;
import java.net.*;
public class RenderToText {
public static void main(String[] args) throws Exception {
String sourceUrlString="data/test.html";
if (args.length==0)
System.err.println("Using default argument of \""+sourceUrlString+'"');
else
sourceUrlString=args[0];
if (sourceUrlString.indexOf(':')==-1) sourceUrlString="file:"+sourceUrlString;
Source source=new Source(new URL(sourceUrlString));
String renderedText=source.getRenderer().toString();
System.out.println("\nSimple rendering of the HTML document:\n");
System.out.println(renderedText);
}
}
我需要一个包含FreeMarker标签的HTML的纯文本表示。问题交给了我一个JSoup的解决方案,但是JSoup会转义FreeMarker标签,从而破坏功能。我还尝试了htmlCleaner(sourceforge),但它会保留HTML头和样式内容(已删除标签)。 https://dev59.com/Q3I_5IYBdhLWcg3wHfSr#1519726
我的代码:
return new net.htmlparser.jericho.Source(html).getRenderer().setMaxLineLength(Integer.MAX_VALUE).setNewLine(null).toString();
maxLineLength
确保行不会在 80 个字符处被人为地换行。
setNewLine(null)
使用与源相同的换行符。
使用Jsoup,我将所有文本都放在同一行中。
因此,我使用了以下代码块来解析HTML并保留换行符:
private String parseHTMLContent(String toString) {
String result = toString.replaceAll("\\<.*?\\>", "\n");
String previousResult = "";
while(!previousResult.equals(result)){
previousResult = result;
result = result.replaceAll("\n\n","\n");
}
return result;
}
不是最好的解决方案,但解决了我的问题 :)
HTMLUtil.textFromHTML(value)
。<dependency>
<groupId>org.clapper</groupId>
<artifactId>javautil</artifactId>
<version>3.2.0</version>
</dependency>