1

I am using Jsoup to get some data from html, I have this code:

System.out.println("nie jest");
StringBuffer url=new StringBuffer("http://www.darklyrics.com/lyrics/");
url.append(args[0]);
url.append("/");
url.append(args[1]);
url.append(".html");

//wyciaganie odpowiednich klas z naszego htmla
Document doc=Jsoup.connect(url.toString()).get();
Element lyrics=doc.getElementsByClass("lyrics").first();
Element tracks=doc.getElementsByClass("albumlyrics").first();

//Jso
//lista sciezek
int numberOfTracks=tracks.getElementsByTag("a").size();

Everything would be fine, I extracthe data I want, but when I do:

lyrics.text()

I get the text with no line breaks, so I am wondering how to leave line breaks in displayed text, I read other threads on stackoverflow on this matter but they weren't helpful, I tried to do something like this:

TextNode tex=TextNode.createFromEncoded(lyrics.text(), lyrics.baseUri());

but I can't get the text I want with line breaks. I looked at previous threads about this like, Removing HTML entities while preserving line breaks with JSoup but I can't get the effect I want. What should I do?

Edit: I got the effect I wanted but I don't think it is very good solution:

for (Node nn:listOfNodes)
            {
                String s=Jsoup.parse(nn.toString()).text();
                if ((nn.nodeName()=="#text" || nn.nodeName()=="h3"))
                {
                    buf.append(s+"\n");

                }
            }

Anyone got better idea?

Community
  • 1
  • 1
Andna
  • 6,539
  • 13
  • 71
  • 120

1 Answers1

1

You could get the text nodes (the text between <br />s) by checking if the node is an instance of TextNode. This should work out for you:

Document document = Jsoup.connect(url.toString()).get();
Element lyrics = document.select(".lyrics").first();
StringWriter buffer = new StringWriter();
PrintWriter writer = new PrintWriter(buffer);

for (Node node : lyrics.childNodes()) {
    if (node.nodeName().equals("h3")) {
        writer.println(((Element) node).text());
    } else if (node instanceof TextNode) {
        writer.println(((TextNode) node).text());
    }
}

System.out.println(buffer.toString());

(please note that comparing the object's internal value should be done by equals() method, not ==; strings are objects, not primitives)

Oh, I also suggest to read their privacy policy.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555