Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I would like to parse an html source string to find a specific tag in Java

So I have the following html source:

<form action='http://example.com' method='get'>

        <P>Some example text here.</P>
        <input type='text' class='is-input' id='agent_name' name='deviceName' placeholder='Device Name'>
        <input type='hidden' name='p' value='firefox'>
        <input type='hidden' name='email' value='[email protected]'>
        <input type='hidden' name='k' value='cITBk236gyd56oiY0fhk6lpuo9nt61Va'>
        <p><input type='submit' class='btn-blue' style='margin-top:15px;' value='Install'></p>
</form>

Unfortunately this html source is saved as a string. I would like to parse it using something like jsoup. and obtain the following String: <input type='hidden' name='k' value='cITBk236gyd56oiY0fhk6lpuo9nt61Va'>

or better yet, only grab the following value: cITBk236gyd56oiY0fhk6lpuo9nt61Va

The problem I'm running into is that:

a) that value: cITBk236gyd56oiY0fhk6lpuo9nt61Va is consistently changing I cannot look for the entire html tag.

So, I am looking for a better way to do this. Here is what I currently have that does not seem to be working:

//tried use thing, but java was angry for some reason
Jsoup.parse(myString);

// so I used this instead. 
org.jsoup.nodes.Document doc = Jsoup.parse(myString);

// in this case I just tried to select the entire tag. Elements
elements = doc.select("<input name=\"k\"
value=\"cITBkdxJTFd56oiY0fhk6lUu8Owt61Va\" type=\"hidden\">");

//yeah this does not seem to work. I assume it's not a string anymorebut a document. Not sure if it 
//would attempt to print anyway.
System.out.println(elements);

so I guess I can't use select, but even if this would work. I was not sure how to place select that part of the tag and place it into a new string.

like image 768
adbarads Avatar asked Oct 19 '25 09:10

adbarads


1 Answers

You can try this way

Document doc = Jsoup.parse(myString);
Elements elements = doc.select("input[name=k]");
System.out.println(elements.attr("value"));

output:

cITBk236gyd56oiY0fhk6lpuo9nt61Va
like image 128
Pshemo Avatar answered Oct 21 '25 23:10

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!