简体   繁体   中英

how to parse html

I have downloaded the Java HtmlParser but I dont know how to use the API for extracting the HTML data. Can you give some example so that I can work on it?

You're talking about HtmlParser ? Rather pick a parser with less verbose API like Jsoup . All you need to learn are then CSS selectors which are already obvious enough to the average frontend developer.

Here's a kickoff example which displays your current question and the names of all answerers:

package com.stackoverflow.q3416036;

import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class Test {

    public static void main(String[] args) throws Exception {
        URL url = new URL("https://stackoverflow.com/questions/3416036");
        Document document = Jsoup.parse(url, 3000);

        String question = document.select("#question .post-text").text();
        System.out.println("Question: " + question);

        Elements answerers = document.select("#answers .user-details a");
        for (Element answerer : answerers) {
            System.out.println("Answerer: " + answerer.text());
        }
    }

}

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM