Jsoup access to HTML select tag

I am new to jsoup and have worked a bit with the html tag. I need to get the value attribute for list selection options based on the text they contain. For instance:

'<select id="list"> <option value="0">First value</option> <option value="1">Second value</option> <option value="2">Third value</option> </select>' 

Do you have an idea how can I tell jsoup to return a value of "1" if it receives a "Second value" as a parameter to search for?

+4
source share
4 answers

This may help you ..

 String demo = "<select id='list'><option value='0'>First value</option><option value='1'>Second value</option><option value='2'>Third value</option></select>"; Document document = Jsoup.parse(demo); Elements options = document.select("select > option"); for(Element element : options) { if(element.text().equalsIgnoreCase("second value")) { System.out.println(element.attr("value")); } } 
+6
source

Here's another solution:

 public String searchAttribute(Element element, String str) { Elements lists = element.select("[id=list]"); for( Element e : lists ) { Elements result = e.select("option:contains(" + str + ")"); if( !result.isEmpty() ) { return result.first().attr("value"); } } return null; } 

Test:

 Document doc = Jsoup.parse(html); // html is your listed html / xml Strign result = searchAttribute(doc, "Second value") // result = 1 
+5
source

Try this code:

 String searchValue = "Second value"; Elements options = doc.select("#list > option"); String value = ""; for (Element option : options) { String text = option.text(); if (text.equals(searchValue)){ value = option.attr("value"); } } 

Hope this helps!

+2
source

I think the simplest solution is:

  Document doc = Jsoup.parse(html); String value = doc.select("#list > option:contains(Second value)").val(); 
+1
source

Source: https://habr.com/ru/post/1432942/


All Articles