Question

Comment puis-je analyser uniquement le texte à partir d'une page Web en utilisant jsoup en utilisant java?

Était-ce utile?

La solution

De cookbook jsoup: http://jsoup.org/cookbook/extracting- données / attributs de texte 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"

Autres conseils

Utilisation des classes qui font partie du 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);
        }
    }
}

Eh bien, voici une méthode rapide j'ai jeté ensemble une fois. Il utilise des expressions régulières pour faire le travail. La plupart des gens conviennent que ce n'est pas une bonne façon de s'y prendre pour le faire. , Utilisez à vos propres risques.

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

a été utilisé dans mon wrapper pour l'API Stack Overflow. Il en était ainsi que testé dans un petit sous-ensemble de balises html.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top