Jsoup get element in value=" "

Lars picture Lars · Sep 25, 2011 · Viewed 14.8k times · Source

I want to find the element "buddyname" and get the element of value= "" in a HTML file which i put into a StringBuffer, in this case 5342test. The element in value= "" can change so i can not search directly for 5342test.

<fieldset style="display:none"><input type="hidden" name="buddyname" value="5342test"/></fieldset> 

How can i do this with jsoup? or is there an easier way, I already tried Pattern/Matcher but that did not work out as i had issues with the Pattern.compile("<input[^>]*?value\\s*?=\\s*?\\\"(.*?)\\\")");

Below some example code. Thank you in advance.

Document doc = Jsoup.parse(page); // page is a StringBuffer
        Elements td = doc.select("fieldset"); 

        for (Element td : tds) { 
          String tdText = td.text();
          System.out.println(tdText);
        } 

Answer

BalusC picture BalusC · Sep 25, 2011

Just use the attribute selector [attrname=attrvalue].

Element buddynameInput = document.select("input[name=buddyname]").first();
String buddyname = buddynameInput.attr("value");
// ...

Do not use regex to parse HTML. It makes no sense if you already have a world class HTML parser at your hands.

See also: