好久没写博客了,再写博客已经从Eclipse转移到Idea了。哈哈,Idea这个东西,开始真不习惯,后来越用越舒服。哈哈
进入正题,Talk is useless, show my code....
首先,maven需要导入的包,先给你们送上,毕竟说好的详细教程。demo里只需要引入jsoup依赖。
<dependencies>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.9.2</version>
</dependency>
</dependencies>
这里先等等,我们先用F12去看下要爬的网站:
看上去是很正常的一个网站,图片用的是<img/>标签。
然后继续show code,主要的代码内容,里面包含很多注释,重点在爬虫,下载图片那边就不多说了,看代码就行。主要代码:
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class TestSpider {
public static void main(String[] args) throws IOException {
String path = "e:/testSpider/";//存放文件夹的目录
File file = new File(path);
if (!file.exists()) {//如果文件夹不存在
file.mkdir();//创建文件夹
}
String sourceUrl = "http://photo.xxxxxxxxxx.com";//目标网站(自己要改)
List<String> pics = getUrls(sourceUrl);//调用下面获取所有链接的方法
downloadPicture(pics, path);//调用下面下载网站的方法
}
public static List<String> getUrls(String sourceUrl) throws IOException {
Document doc = Jsoup.connect(sourceUrl).get();//获取整个DOM节点
Elements links = doc.select("img[src]");//获取所有img节点
List<String> pics = new ArrayList<String>();//集合存放所有图片链接
for (Element element : links) {
//控制台输出element:<img src="http://abc.jpg">
String src = element.attr("src");
//控制台输出src:"http://abc.jpg"
pics.add(src);
}
return pics;
}
//链接url下载图片
private static void downloadPicture(List<String> urlList, String path) {
int i = 0;//图片命名用
for (String oneUrl : urlList) {
URL url;
try {
url = new URL(oneUrl);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path + i + ".jpg"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
i++;
}
}
}
不多说,直接拷过去就可以直接使用,记得改网址。
然后看E盘,已经下载好了:
基本上都爬下来了。
Jsoup解析dom还是很强大的,更多的API还要多多学习。这里只是一个简单的demo,初步使用Jsoup,至于爬虫的进阶玩法(模拟登陆,翻页,反爬虫等等),大家有兴趣可以深入学习。
文章原创,有意见或者建议,可以留言,如有转载,请注明出处,谢谢。