利用Jsoup爬取网站的图片,保存到本地

jsoup 是一款Java 的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的API,可通过DOM,CSS以及类似于jQuery的操作方法来取出和操作数据。

学习的过程中可能会用到其他的API,下面一个类做一下简单的测试

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
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 JsoupTest {
public static void main(String[] args) throws IOException {
    JsoupTest jsoupTest = new JsoupTest();
    String url = "http://tieba.baidu.com/p/4549504175";
    // 1.jsoup 的简单应用
    jsoupTest.getHtmlElements(url);
}
 
private static int count = 0;
 
// 爬取网络的图片到本地
public void saveToFile(String destUrl) {
 
    FileOutputStream fos = null;
    BufferedInputStream bis = null;
    HttpURLConnection httpUrl = null;
    URL url = null;
    int BUFFER_SIZE = 1024;
    byte[] buf = new byte[BUFFER_SIZE];
    int size = 0;
    try {
        url = new URL(destUrl);
        httpUrl = (HttpURLConnection) url.openConnection();
        httpUrl.connect();
        bis = new BufferedInputStream(httpUrl.getInputStream());
        String imgName = destUrl.substring(7, destUrl.lastIndexOf("."));
        System.out.println(imgName);
        File dir = new File("f://img");
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File("f:\\img\\haha" + count + ".jpg");
        System.out.println(file.getAbsolutePath());
 
        fos = new FileOutputStream(file);
        while ((size = bis.read(buf)) != -1) {
            fos.write(buf, 0, size);
        }
        fos.flush();
    } catch (IOException e) {
        System.out.println("IOException");
    } catch (ClassCastException e) {
        System.out.println("ClassCastException");
    } finally {
        count++;
        try {
            fos.close();
            bis.close();
            httpUrl.disconnect();
        } catch (IOException e) {
        } catch (NullPointerException e) {
        }
    }
}
 
    // 解析url的元素
    private void getHtmlElements(String url) {
        try {
            Document doc = Jsoup.connect(url).get();
            // 获取后缀名为jpg的img元素
            Elements pngs = doc.select("img[src$=.jpg]");
            for (Element element : pngs) {
                saveToFile(element.attr("src"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

参考资料

1.http://www.open-open.com/jsoup/parsing-a-document.htm

2.http://blog.csdn.net/withiter/article/details/15339579

3.http://blog.csdn.net/csh159/article/details/7310009

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
如果页面使用 JavaScript 动态加载图片,那么使用 Jsoup 无法直接获取到这些图片的 URL,需要使用其他技术来模拟浏览器行为,比如使用 Selenium WebDriver。 以下是使用 Selenium WebDriver 和 Jsoup 爬取动态页面图片的示例代码: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.List; public class Main { public static void main(String[] args) { // 设置 Selenium WebDriver 的路径 System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // 创建 ChromeDriver 实例 WebDriver driver = new ChromeDriver(); // 打开目标页面 driver.get("https://example.com"); // 等待页面加载完成 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } // 使用 Jsoup 解析 HTML Document doc = Jsoup.parse(driver.getPageSource()); // 获取图片元素 Elements imgElements = doc.select("img"); // 遍历图片元素 for (int i = 0; i < imgElements.size(); i++) { // 获取图片 URL String imgUrl = imgElements.get(i).attr("src"); // 下载图片 // ... } // 关闭 ChromeDriver driver.quit(); } } ``` 这段代码首先创建了一个 Selenium WebDriver 实例,打开了目标页面,并等待页面加载完成。然后,使用 Jsoup 解析 HTML,获取所有的图片元素,遍历图片元素并获取图片 URL,最后可以使用 Java 的网络编程 API 或第三方库(如 Apache HttpClient)下载图片。最后,关闭 ChromeDriver。需要注意的是,在实际应用中,需要根据实际情况设置适当的等待时间,以防止页面未完全加载完成导致获取不到图片元素。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值