user2823083
user2823083

Reputation: 445

Accessing a class element using jsoup

This is the html file:

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Title</title>
    </head>
    <body>

    <h1>Demo</h1>
     <div class="eta">
        <h2>Text</h2>
        <h2 class="strike">Text1</h2>
        <div class="del">
          <p>Text2</p>
        </div>
        <p class="desc">Text3</p>
      </div>
    </body>
    </html>

I want to access first element of class="eta" which is Text. I wrote the following code:

public static void main(String[] args) {
        Document doc;
        Document doc1;
        try {

            File input = new File("/path/sample.html");
            doc1 = Jsoup.parse(input, "UTF-8");

            Elements details2 = doc1.getElementsByClass("eta");
            String status2 = details2.first().text();
            System.out.println(status2);


        } catch (IOException e) {
            e.printStackTrace();  
        }
    }

This program outputs the following: Text Text1 Text2 Text3

Whereas, I want to extract only Text. How can I do that?

Upvotes: 0

Views: 85

Answers (1)

ShinyJos
ShinyJos

Reputation: 1487

Elements divs = doc1.select("eta");
Element firstDiv = divs.get(0);
System.out.println(firstDiv.text());

Upvotes: 1

Related Questions