2010-08-31 168 views
18

朋友的 我必须从url解析描述,其中解析的内容有很少的html标记,所以我怎样才能将它转换为纯文本。如何将HTML文本转换为纯文本?

+0

你有什么精确的要求?你需要去掉HTML标签吗?提取特定标签的内容? – 2010-08-31 10:05:18

+0

我可以能够提取的内容,但内容有

ZCC dsdfsf ddfdfsf

sfdfdfdfdf, 像上面我得到我的数据,但我需要一个简单的纯text.without那些HTML标签 – MGSenthil 2010-08-31 10:54:37

+0

有类似的问题在这里很好的答案:http://stackoverflow.com/questions/1518675/open-source-java-library-for-html-to-text-conversion/1519726#1519726。我用杰里科,它工作正常。 – 2013-09-03 09:49:43

回答

1

我建议通过解析jTidy原始HTML应该给你输出,你可以写XPath表达式反对。这是我发现的刮取HTML的最强大的方法。

16

刚刚摆脱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>元素需要一个单独的处理,有可能与CDATA块>字符(例如javascript)弄乱了正则表达式等。

+1

很好,你澄清了所有的复杂性! – ankitjaininfo 2010-08-31 13:18:32

+0

对于一些为什么这将不适用于一般情况下的背景,并且不会是f(u | oo)l-proof:[RegEx匹配除XHTML自包含标记以外的开放标记](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – 2017-04-12 13:00:29

6

您可以使用这一行删除html标签并将其显示为纯文本。

htmlString=htmlString.replaceAll("\\<.*?\\>", ""); 
0

如果要解析象浏览器显示,使用方法:

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); 
    } 
} 

我希望这将有助于分析也表在浏览器格式。

感谢, Ganesh神

+0

downvoters请解释他们为什么downvote? – koppor 2016-12-11 21:40:30