How to Parse Only Text from HTML

how can i parse only text from a web page using jsoup using java?

9
задан NawaMan 17 August 2010 в 22:47
поделиться

3 ответа

Из поваренной книги 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"
18
ответ дан 4 December 2019 в 11:03
поделиться

Итак, вот быстрый метод, который я однажды собрал. Он использует регулярные выражения для выполнения своей работы. Большинство людей согласятся, что это не лучший способ делать это. ТАК, используйте на свой страх и риск.

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
ответ дан 4 December 2019 в 11:03
поделиться

Использование классов, входящих в 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);
        }
    }
}
1
ответ дан 4 December 2019 в 11:03
поделиться
Другие вопросы по тегам:

Похожие вопросы: