如何在Java中从HTML中获取特定值?

4
我正在开发一款应用程序,它可以显示黄金价格并生成相关的图表。我发现了一个提供黄金价格信息的网站,它会定期更新此信息。我的问题是如何从 HTML 页面中提取特定的数值。
以下是需要提取的链接:http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/,该网页包含以下标签和内容。
<p><em>10 gram gold Rate in pune = Rs.31150.00</em></p>     

这是我用于提取信息的代码,但我没有找到提取特定内容的方法。

public class URLExtractor {

private static class HTMLPaserCallBack extends HTMLEditorKit.ParserCallback {

    private Set<String> urls;

    public HTMLPaserCallBack() {
        urls = new LinkedHashSet<String>();
    }

    public Set<String> getUrls() {
        return urls;
    }

    @Override
    public void handleSimpleTag(Tag t, MutableAttributeSet a, int pos) {
        handleTag(t, a, pos);
    }

    @Override
    public void handleStartTag(Tag t, MutableAttributeSet a, int pos) {
        handleTag(t, a, pos);
    }

    private void handleTag(Tag t, MutableAttributeSet a, int pos) {
        if (t == Tag.A) {
            Object href = a.getAttribute(HTML.Attribute.HREF);
            if (href != null) {
                String url = href.toString();
                if (!urls.contains(url)) {
                    urls.add(url);
                }
            }
        }
    }
}

public static void main(String[] args) throws IOException {
    InputStream is = null;
    try {
        String u = "http://www.todaysgoldrate.co.in/todays-gold-rate-in-pune/";   
        //Here i need to extract this content by tag wise or content wise....  

感谢您提前阅读……
2个回答

2
您可以使用像 Jsoup 这样的库。
您可以从这里获取 --> 下载 Jsoup 这是它的 API 参考文档 --> Jsoup API 参考文档 使用 Jsoup 解析 HTML 内容非常容易。
以下是一个示例代码,可能对您有所帮助...
public class GetPTags {

           public static void main(String[] args){

             Document doc =  Jsoup.parse(readURL("http://www.todaysgoldrate.co.intodays-gold-rate-in-pune/"));
             Elements p_tags = doc.select("p");
             for(Element p : p_tags)
             {
                 System.out.println("P tag is "+p.text());
             }

            }

        public static String readURL(String url) {

        String fileContents = "";
        String currentLine = "";

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
            fileContents = reader.readLine();
            while (currentLine != null) {
                currentLine = reader.readLine();
                fileContents += "\n" + currentLine;
            }
            reader.close();
            reader = null;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage(), "Error Message", JOptionPane.OK_OPTION);
            e.printStackTrace();

        }

        return fileContents;
    }

}

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接