jsoup获取图片示例

时间:2022-01-30 16:35:07
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection; import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; // 爬取图片
public class Baidu { public static void main(String[] args) {
String urlPath = "http://www.*****.com/chemo/2043_2.html";
int index = 2;
for (int j = 0; j <= 20; j++) {
urlPath = "http://www.****.com/chemo/2043_" + (index++) + ".html"; File f = new File("F:/imgs");
if (!f.exists()) {
f.mkdirs();
} Document doc;
try {
doc = Jsoup.connect(urlPath).timeout(10000).get(); // 获取后缀为jpg的图片的元素集合
Elements pngs = doc.select("img[src$=.jpg]");
// 遍历元素
for (Element e : pngs) {
String src = e.attr("src");// 获取img中的src路径
// 获取后缀名
String imageName = src.substring(src.lastIndexOf("/") + 1,
src.length());
// 连接url
URL url;
try {
url = new URL(src);
URLConnection uri = url.openConnection();
// 获取数据流
InputStream is = uri.getInputStream();
// 写入数据流
OutputStream os = new FileOutputStream(new File(
"F:/imgs", imageName)); byte[] buf = new byte[3072];
int i = 0;
while ((i = is.read()) != -1) {
os.write(i);
}
                os.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} } } catch (IOException e2) {
e2.printStackTrace();
}
} } }

这里用的是jsoup1.6.3jar

研究了一天时间,说说碰到的难题。我这里抓取的是以.jpg为主的图片.

当时没有获取图片的后缀名,每次往电脑上下载图片总是新建一个空的文件夹。一定要获取到图片的后缀名才行。

还有一点就是我这个方法不一定适合所有的网站,不同网站的src地址不一样,需要注意一下。

我这个是有20多页的图片,简单用了个循环,每页的地址都有规律,找到规律就手到擒来了。

刚研究,如有高手,还望赐教。