I'm new to jsoup and having a bit of trouble with html tag. I need to get value attribute of select list options based on a text they contain. For example:
'<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 I can tell jsoup to return the value "1" if it gets a "Second value" as a parameter for a search?
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
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"));
}
}
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 it helps!
I think the simplest solution is:
Document doc = Jsoup.parse(html);
String value = doc.select("#list > option:contains(Second value)").val();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.