如何从HTML中解析文本

问题描述:

如何仅使用java解析使用jsoup的网页中的文本?如何从HTML中解析文本

从jsoup食谱:http://jsoup.org/cookbook/extracting-data/attributes-text-html

String html = "<p>An <a href='http://example.com/'><b>example</b></a> link.</p>"; 
Document doc = Jsoup.parse(html); 
String text = doc.body().text(); // "An example link" 
+0

如何排除不可见元素? (例如:display:none) – Ehsan 2013-06-19 06:51:26

嗯,这里是一个快速的方法我一起扔一次。它使用正则表达式完成工作。大多数人会同意这不是一个好办法。所以,使用风险自负。

public static String getPlainText(String html) { 
    String htmlBody = html.replaceAll("<hr>", ""); // one off for horizontal rule lines 
    String plainTextBody = htmlBody.replaceAll("<[^<>]+>([^<>]*)<[^<>]+>", "$1"); 
    plainTextBody = plainTextBody.replaceAll("<br ?/>", ""); 
    return decodeHtml(plainTextBody); 
} 

这最初是在我的API封装器中用于堆栈溢出API。所以,它只在html标签的一小部分下进行测试。

+0

嗯...为什么不使用简单的正则表达式:'replaceAll(“] +>”,“”)'? – Crozin 2010-08-17 22:28:04

+0

@Crozin,好吧,我在教自己如何使用我猜的后向引用。它看起来像你的可能也会工作。 – jjnguy 2010-08-17 22:31:03

+0

这伤害! - > http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – sleeplessnerd 2011-08-27 13:54:15

使用是JDK的一部分类:

import java.io.*; 
import java.net.*; 
import javax.swing.text.*; 
import javax.swing.text.html.*; 

class GetHTMLText 
{ 
    public static void main(String[] args) 
     throws Exception 
    { 
     EditorKit kit = new HTMLEditorKit(); 
     Document doc = kit.createDefaultDocument(); 

     // The Document class does not yet handle charset's properly. 
     doc.putProperty("IgnoreCharsetDirective", Boolean.TRUE); 

     // Create a reader on the HTML content. 

     Reader rd = getReader(args[0]); 

     // Parse the HTML. 

     kit.read(rd, doc, 0); 

     // The HTML text is now stored in the document 

     System.out.println(doc.getText(0, doc.getLength())); 
    } 

    // Returns a reader on the HTML data. If 'uri' begins 
    // with "http:", it's treated as a URL; otherwise, 
    // it's assumed to be a local filename. 

    static Reader getReader(String uri) 
     throws IOException 
    { 
     // Retrieve from Internet. 
     if (uri.startsWith("http:")) 
     { 
      URLConnection conn = new URL(uri).openConnection(); 
      return new InputStreamReader(conn.getInputStream()); 
     } 
     // Retrieve from file. 
     else 
     { 
      return new FileReader(uri); 
     } 
    } 
}