Search code examples
javascriptandroidandroid-studiojsoupscreen-scraping

Get the second word from the div using JSoup


My code I gets all the words in the div. What do I need to do to only get the second word that is inside the div?

Eg:

<div id="div01"> FIRSTWORD SECONDWORD </DIV>

My code:

Document doc = Jsoup.connect(url).get();

Elements statistics = doc.select(div.div01);

textDiv1 = statistics.text();

Solution

  • Why not just do it like how you'd get the second word in a Java string?

    String secondWord = line.split(" ")[1]; //add your own checks to avoid out of bounds or null exceptions.
    

    Example extending what you have already:

    if (textDiv1 != null) {
        String[] words = textDiv1.split(" ");   //split our text into individual words, which are separated by spaces
        if (words.length >= 2) {                //there are at least two words
            String secondWord = words[1];
        }
        //otherwise, there is no second word, so you can handle it here
    }
    //there is no text found as textDiv1 is null
    

    ** Unless your second word happens to be in its own element, this isn't something JSOUP would distinguish **