简体   繁体   English

Java从网页获取单个元素

[英]Java get single element from webpage

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 我知道如何用C做到这一点,但想知道在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 我需要从网页获取该值到String变量中

You can use jsoup for that: 您可以为此使用jsoup

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. 您可能还需要遵循重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM