Jsoup get form parameters example

Let us discuss how to get form parameters using Jsoup API with the help of below example.

Follow the below steps:

1. Create a HTML file containing form with some input parameters.
2. Use parse(File in, String charsetName) method of Jsoup class which returns Document object after processing the file object.
3. Get form by using getElementById() method of Connection class.
4. Get input parameters of the form.
5. Iterate and process parameters.

Example:

JsoupParseHTMLFromString.java
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
/**
* This class is used get meta data from HTML using Jsoup.
* @author javawithease
*/

public class JsoupGetParameter {
public static void main(String args[]){
Document document;
try {
//Get Document object after parsing the html file.
document=Jsoup.parse(
new File("D:\\JsoupParameterTest.html"),"utf-8");
 
//Get the form by id.
Element testForm = document.getElementById("testForm");
 
//Get input parameters of the form.
Elements inputElements = testForm.getElementsByTag("input");
 
//Iterate parameters and print name and value.
for (Element inputElement : inputElements) {
String key = inputElement.attr("name");
String value = inputElement.attr("value");
System.out.println("Parameter Name: " + key);
System.out.println("Parameter Value: " + value);
System.out.println("");
}
} catch (IOException e) {
e.printStackTrace();
}
 
}
}

Output:

Parameter Name: name
Parameter Value: Richi
 
Parameter Name: password
Parameter Value: sahdev
 
Parameter Name: submit
Parameter Value: Submit

No comments: