• Breaking News

    Wednesday, 14 October 2015

    GET ELEMENT BY ID AND CLASS IN JSOUP




    In this tutorial we will see how we retrieve html element by ID and class in java by using JSOUP..

    JSOUP provide below method to retrieve element

    1.  getElementById() method of Document Class to get element by ID in java code.
       
         Element elementByID = doc.getElementById("getElementByID"); 


    2. getElementsByClass() method of Document Class to get element by Class in java code.

         Elements elementByClass = doc.getElementsByClass("getElementByClass");


    Below is example

    package com.kodemaker;
    
    import java.io.IOException;
    
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    public class JSOUPTest {
     
     public static void main(String[] args) throws IOException {
      Document doc = Jsoup.parse("<input type='text' id='getElementByID' value='jsoup'>+"
        + "<input type='text' class='getElementByClass' value='jsoup1'>"
        + "<input type='text' class='getElementByClass' value='jsoup2'>");
      
      Element elementByID = doc.getElementById("getElementByID");  
      
      System.out.println("Element By ID ");  
      
      System.out.println(elementByID.val());
      
      Elements elementByClass = doc.getElementsByClass("getElementByClass");
      
      System.out.println("Element By Class");  
        
      for(Element e : elementByClass){
       System.out.println(e.val());  
      }
      
     }
    }
    


    Output of above example

    Element By ID 
    jsoup
    Element By Class
    jsoup1
    jsoup2
    

    No comments:

    Post a Comment