How to get a value from HTML file in Java?

2019-02-18 13:40发布

I need to get a value ("abc" in below example) from HTML file that looks like this:

          <input type="hidden" name="something" value="abc" />

As i found out from other posts, i should be using one of the HTML parsers (not regex). Could you please tell me which one to use or show a code sample.

Thank you.

2条回答
欢心
2楼-- · 2019-02-18 13:45
混吃等死
3楼-- · 2019-02-18 13:56

You could use Jsoup for this.

File file = new File("/path/to/file.html");
Document document = Jsoup.parse(file, "UTF-8");
Element something = document.select("input[name=something]").first();
String value = something.val();
System.out.println(value); // abc
// ...

Or shorter:

String value = Jsoup.parse(new File("/path/to/file.html"), "UTF-8").select("input[name=something]").first().val();
System.out.println(value); // abc
// ...

See also:

查看更多
登录 后发表回答