1

Hi so after some searching still not found an answer but i would like to get a single element of a webpage to a String Variable. I know how to do this in C but would like to know in java

eg:

document.nav(the webpage)
String value = document.getElementbyid(theid)

Thanks

so eg:

some webpage has

<body>
<P id=element1>the value i want</p>
</body>

and i need to get that value from the webpage into a String variable

user3329114
  • 13
  • 1
  • 6
  • What exactly would you like to get? The complete html of the element including tags or the text. Short minimal example html would be helpful too. And what is the type of document (or what is your input data (InputStream, Url, String or ...))? – fabian Jun 07 '14 at 14:36
  • https://stackoverflow.com/questions/24772828/how-to-parse-html-table-using-jsoup – Marek Schimmel Jan 08 '19 at 16:33

1 Answers1

2

You can use jsoup for that:

String url = "http://www.example.com"; // or whatever goes here
Document document = Jsoup.connect(url).followRedirects(false).timeout(60000/*wait up to 60 sec for response*/).get();
String value = document.body().select("#element1" /*css selector*/).get(0).text();

If you need another input format please refer to the cookbook

It's not really necessary to specify timeout ect. for the connection. You could just use

Document document = Jsoup.connect(url).get();

I only included the timeout if the webpage takes really long to load. You also may want to follow redirects.

fabian
  • 80,457
  • 12
  • 86
  • 114