开门见山,先说需求:获取一个网页的源码,然后解析对应的图片地址,最后将图片下载到本地
网页:点击直达
需要下载的图片所在的地方:
将上图中
- 元素里的图片(大概有一百多张)下载到本地,下载不要使用多线程,太快怕锁ip。请问该怎么做?
网页:点击直达
需要下载的图片所在的地方:
该回答引用自ChatGPT
根据你的使用场景修改了下,你可以试试。我自己试着是好使的
Java可以使用Jsoup库来解析HTML源码,然后通过正则表达式或者CSS选择器来获取图片地址。最后使用Java的IO流将图片下载到本地。
下面是一个简单的Java爬取图片的示例代码:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class ImageCrawler {
public static void main(String[] args) throws IOException {
String url = "https://pvp.qq.com/web201605/item.shtml";
String saveFolder = "D:\\Temp";
Document doc = Jsoup.connect(url).get();
Elements imgs = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
for (Element img : imgs) {
try {
String imgUrl = img.attr("src");
if (imgUrl == null || imgUrl == "") {
continue;
}
if (!imgUrl.startsWith("http")) {
imgUrl = "https:" + imgUrl;
}
downloadImage(imgUrl, saveFolder);
System.out.println("Image " + imgUrl + " downloaded.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static void downloadImage(String imgUrl, String saveFolder) throws IOException {
URL url = new URL(imgUrl);
InputStream in = url.openStream();
String fileName = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
FileOutputStream out = new FileOutputStream(saveFolder + fileName);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
in.close();
out.close();
}
}
这个示例代码中,首先使用Jsoup库获取指定网页的HTML源码,然后使用CSS选择器来获取所有的图片元素。接着遍历每个图片元素,获取其src属性值作为图片的地址。最后通过Java的IO流将图片下载到本地。在实际使用中,需要根据具体情况进行修改和优化。
jsoup pom 依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.1</version>
</dependency>