java 下载汽车图片代码
时间: 2024-01-01 17:57:47 浏览: 35
以下是使用Java中的Jsoup库和Java IO来下载汽车图片的示例代码:
```java
import java.io.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
public class DownloadCarImages {
public static void main(String[] args) throws IOException {
// 创建文件夹来保存图片
File dir = new File("./car_images");
if (!dir.exists()) {
dir.mkdir();
}
// 设置搜索关键词和下载图片的数量
String search_term = "car";
int num_images = 1000;
// 构造搜索url
String url = "https://www.google.com/search?q=" + search_term + "&tbm=isch";
// 发送get请求并解析响应内容
Document doc = Jsoup.connect(url).get();
// 提取所有图片标签
Elements imgTags = doc.getElementsByTag("img");
// 下载图片
int count = 0;
for (Element imgTag : imgTags) {
// 获取图片链接
String imgUrl = imgTag.attr("src");
try {
// 发送get请求并以字节流形式保存图片
URL urlObj = new URL(imgUrl);
InputStream in = urlObj.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream("./car_images/" + count + ".jpg"));
int i;
while ((i = in.read()) != -1) {
out.write(i);
}
in.close();
out.close();
count++;
// 控制下载数量
if (count == num_images) {
break;
}
} catch (IOException e) {
continue;
}
}
}
}
```
请注意,这只是一个示例代码,您需要根据实际情况进行修改,比如设置合适的搜索关键词和下载数量,以及处理异常情况等。同时,根据不同的网站和图片版权,下载图片可能涉及到法律问题,请您谨慎使用。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)