用java语言写一个从http://www.nmc.cn/publish/radar/chinaall.html网页爬取雷达图片的程序
时间: 2023-12-23 19:03:07 浏览: 123
下面是一个使用Java语言和Jsoup库爬取http://www.nmc.cn/publish/radar/chinaall.html网页上雷达图片的程序:
```java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
public class RadarImageCrawler {
public static void main(String[] args) throws IOException {
String url = "http://www.nmc.cn/publish/radar/chinaall.html";
Document doc = Jsoup.connect(url).get();
Elements imgElements = doc.select("#container > div > div > img");
for (Element imgElement : imgElements) {
String imgUrl = imgElement.absUrl("src");
if (imgUrl.endsWith(".png")) {
System.out.println("Downloading " + imgUrl);
String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
saveImage(imgUrl, fileName);
}
}
}
private static void saveImage(String imgUrl, String fileName) throws IOException {
URL url = new URL(imgUrl);
BufferedInputStream in = new BufferedInputStream(url.openStream());
FileOutputStream out = new FileOutputStream(fileName);
byte[] buf = new byte[1024];
int n = 0;
while ((n = in.read(buf)) != -1) {
out.write(buf, 0, n);
}
in.close();
out.close();
System.out.println("Saved " + fileName);
}
}
```
这个程序使用了Jsoup库来解析HTML文档,查找页面上所有的图片元素,并下载URL以“.png”结尾的图片。下载的图片将在程序的运行目录下保存。注意,下载图片可能需要一段时间,具体时间取决于网络速度和图片大小。
阅读全文