zoukankan      html  css  js  c++  java
  • 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();
                        }
                    }
            
            
    
        }
    
    }
  • 相关阅读:
    mysql数据库常用命令
    二维码的生成--后台版
    软件构建--目录
    软件构建--项目总结
    软件构建--产品测试
    软件构建--产品研发
    软件构建--系统设计
    百度分享代码
    JS定时跳转URL并输出剩余秒数
    c#生成word文档
  • 原文地址:https://www.cnblogs.com/liushisaonian/p/7110700.html
Copyright © 2011-2022 走看看