一、代码
1.代码
ImgServlet代码:
package web;
import org.apache.commons.io.IOUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
@WebServlet("/img")
public class ImgServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("进来了");
//1.根据网址获取它的网页源代码文档对象
Document doc = Jsoup.connect("http://192.168.31.249:8080/zyz/").get();
System.out.println(doc);
//2.从文档doc对象中找到所有图片标签img
Elements es = doc.select("img[src]");
//3.遍历得到每一个图片标签
for (Element e : es) {
String src = e.attr("src");
System.out.println(src);
getImg(src);
}
}
//下载图片的方法
public void getImg(String imgPath){
try {
//1.借助URL--可以将网页上的图片以字节流的形式加载到程序中
InputStream is = new URL("http://192.168.31.225:8080/zyz/" + imgPath).openStream();
//2.指定一个图片保存路径--具体到文件名
FileOutputStream os = new FileOutputStream("D:\\福利图片/"+System.currentTimeMillis()+".jpg");
//3.io工具类,对接两个流
IOUtils.copy(is,os);
} catch (IOException e) {
e.printStackTrace();
}
}
}
index.jsp代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首页</title>
</head>
<body>
<input type="button" onclick="fun1()" value="开始爬图">
</body>
<script>
function fun1() {
location.href='/jml/img';
}
</script>
</html>
需要的jar包:
总结
以上就是通过servlet来实现爬虫爬取图片下载的全部代码。