如何使用Java获取div标签包含的文本?

时间:2015-12-25 06:57:33

标签: java

我正在制作一个应用程序,使用Jsoup从网站上检索星座运势。这是我的代码:

import java.util.Scanner;

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

import java.io.IOException;


public class Horoscope {

    public static void main(String[] args) throws IOException {

        Scanner input = new Scanner(System.in);
        String url = "http://www.horoscope.com/us/horoscopes/general/horoscope-general-daily-today.aspx?sign=";
        String c;
        int num = 0;

        System.out.println("Select your horoscope:\n1) Aries\n2) Taurus\n3) Gemini\n4) Cancer\n5) Leo\n6) Virgo\n7) Libra\n8) Scorpio\n9) Sagittarius\n10) Capricorn\n11) Aquarius\n12) Pisces\nQ: Exit");
        do {
            System.out.print("Your selection: ");

            c = input.next();

            if (c.toLowerCase().charAt(0) == 'q')
                System.exit(0);

            try {
                num = Integer.parseInt(c);
            } catch(NumberFormatException e) {
                System.out.println("Please enter a digit!");
                continue;
            }
        } while (num < 1 || num > 12);

        url = url + c.charAt(0);

        Document doc = Jsoup.connect(url).get();
        Elements horoscopes = doc.getElementsByClass("block-horoscope-text f16 l20");

        for (Element horoscope : horoscopes)
            System.out.println(horoscope.text());

        input.close();
    }

}

我没有从中得到我的星座。我做错了什么?

另外,在java中,如何编写更多的模块化代码?例如,这段代码。我是初学者。

1 个答案:

答案 0 :(得分:1)

Elements tds = doc.select("div[class=\"block-horoscope-text f16 l20\"]");
for (org.jsoup.nodes.Element td : tds)
        System.out.println(td.text());