嗨,经过一番搜索后仍然没有找到答案,但我想将网页的单个元素获取到字符串变量。我知道如何在 C 中执行此操作,但想知道如何在 Java 中执行此操作
例如:
document.nav(the webpage)
String value = document.getElementbyid(theid)
谢谢
所以例如:
某些网页有
<body>
<P id=element1>the value i want</p>
</body>
我需要将该值从网页获取到字符串变量
最佳答案
您可以使用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();
如果需要其他输入格式请引用the cookbook
实际上没有必要指定超时等。用于连接。你可以使用
Document document = Jsoup.connect(url).get();
我只在网页加载时间很长的情况下才包含超时。您可能还想遵循重定向。
关于Java从网页中获取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24098202/