1.新建maven项目
pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>tiebei</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.13.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<configuration>
<archive>
<manifest>
<mainClass>
DownloadGirl
</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.创建java类
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class DownloadGirl {
public static void main(String[] args) throws IOException {
// 1.模拟人类打开一个网页
Document document = Jsoup.connect("https://699pic.com/tupian/meinv.html").get();
// 2.在网页中查找图片(很多图片)
Elements elements = document.select("img.lazy");
System.out.println(elements.size());
// 文件路径
String filePath = System.getProperty("user.dir") + File.separator + "images" + File.separator;
// 创建目录
creatDir(filePath);
// 3.迭代(循环)一个一个处理
for(int i= 0 ; i<elements.size() ; i++){
String s= elements.get(i).attr("data-original");
System.out.println(s);
// 根据图片的地址(是不完整的),拼凑一个完整的图片地址
URL imgUrl = new URL("https:"+s);
// 先和图片保持有效的连接
URLConnection connection = imgUrl.openConnection();
// 为每一张图片 创建输入流
InputStream ru = connection.getInputStream();
// 为每一张图片 创建输出流
FileOutputStream chu = new FileOutputStream(new File(filePath + i +".jpg"));
// 4.拿一个图片,就下载一个图片
// 每读取一次,将读取的字节数据放在里面( 每次运输数据的背包)
byte bs[] = new byte[1024];
// 每次读取的字节数
int count = 0 ;
while( (count= ru.read(bs) ) != -1 ){
chu.write(bs, 0, count);
}
// 释放资源,避免浪费,提高性能
chu.close();
ru.close();
}
}
private static void creatDir(String filePath) {
File dir = new File(filePath);
if (dir.exists()) {
// 删除
deleteDir(dir);
} else {
dir.mkdir();
}
}
public static void deleteDir(File dir) {
if (dir.isDirectory()) {
for (String fileStr : dir.list()) {
String filePath = dir.getPath() + File.separator + fileStr;
deleteDir(new File(filePath));
}
} else {
dir.delete();
System.out.println("删除文件" + dir.getAbsolutePath());
}
}
}
3.打包的时候双击这个
会在target目录生成带jar依赖的jar包。
-jar-with-dependencies结尾的JAR包
最后,命令行运行java -jar xxx.jar包就行。
----------------
更进一步的爬虫,可以看我的第二篇文章
https://blog.csdn.net/feifeiwuxian/article/details/112366469
下面的文章可以扩展参考下。