jsoup简单爬虫页面

//需要的jar包是jsoup-1.10.3.jar
//将下面的运行即可
public class JsoupDemo2 {

    public static void main(String[] args) throws IOException {
        
        String baseURL = "http:";
        Set<String> imgs = new HashSet<>(); // 储存爬取到的图片地址


            Document doc = Jsoup.connect(baseURL).get();
            // 选择png|jpg|jpeg图片,,,其实还可以选择gif,只不过要处理下
            Elements elements = doc.select("img[src~=(?i)\.(png|jpe?g)]");
            for (Element e : elements) {
                // 替换开头为//为http://
                imgs.add(e.attr("src").replaceFirst("^//", "http://"));
            }
            
        for (String img : imgs) {
            System.out.println(img);
            try  
            {  
                URL url = new URL(img);
                URLConnection conn = url.openConnection();
                InputStream is = conn.getInputStream();
                 byte[] bs = new byte[1024];
                    // 读取到的数据长度
                    int len;
                    // 输出的文件流
                    FileOutputStream os = new FileOutputStream("F:\jsoup\"+new Random().nextInt(10000)+".jpg");
                    // 开始读取
                    while ((len = is.read(bs)) != -1) {
                      os.write(bs, 0, len);
                    }
                    // 完毕,关闭所有链接
                    os.close();
                    is.close();
                }catch(Exception e) {
                    e.printStackTrace();
                    }
                }
        
        

    }

}
原文地址:https://www.cnblogs.com/liushisaonian/p/7110700.html