B. Cook
B. Cook

Reputation: 13

How do I get the text enclosed by div tags using Java?

I am making an app to retrieve the horoscope from a website using Jsoup. Here's my code:

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

}

I'm not getting my horoscope from that. What am I doing wrong?

Also, in java, how can I write more modular code? For example, this code. I am a beginner.

Upvotes: 1

Views: 78

Answers (1)

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

Upvotes: 1

Related Questions