Java简单的爬虫实践

2021-05-08  本文已影响0人  HelloWorld丶小工匠

简介
实现基于Jsoup来爬取网页上图片并下载到本地
环境
JDK 1.8
IntelliJ Idea 2020
Jsoup 1.13.1

引入jar包jsoup

   <dependency>
        <groupId>net.sourceforge.htmlunit</groupId>
        <artifactId>htmlunit</artifactId>
        <version>2.27</version>
    </dependency>
    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.8.3</version>
    </dependency>    

实现代码思路:

1、定义需要下载初始路径,可以随机找个图片多的网页地址

2、获取页面内容,定义方法getHtml(String url)

3、获取页面内容图片路径,定义方法getImgSrcListFromHtml(String html)

4、从页面内容中获取下一个页面路径,定义方法getNextPageUrl(String html)

5、下载图片,downloadImg(List<String> list, String filepath),实现:通过获取的流转成byte[]数组,再通过FileOutputStream写出

6、InputStream流转换byte[]定义方法getBytesFromInputStream(InputStream inputStream),实现:ByteArrayOutputStream的toByteArray()方法转byte[];

实现代码:

  public static void main(String[] args) throws Exception {
            //链接到目标地址
            Connection connect = Jsoup.connect(url);
            //设置useragent,设置超时时间,并以get请求方式请求服务器
            Document document = connect.userAgent("Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)")
                    .timeout(6000).ignoreContentType(true).get();
            Thread.sleep(100);
            //获取指定标签的数据
            Element elementById = document.getElementById("content_left");
            //输出文本数据
            System.out.println(elementById.text());
            //输出html数据
            //System.out.println(elementById.html());

            //获取所有图片链接
            Elements imgtag = document.getElementsByTag("img");

            for (int i = 0; i < imgtag.size(); i++) {
                if (imgtag.get(i).attr("src").startsWith("http")
                        &&(
                        imgtag.get(i).attr("src").endsWith("jpg")||
                                imgtag.get(i).attr("src").endsWith("jpeg")
                        )
               ) {
                    String imgUrl=imgtag.get(i).attr("src");
                    System.out.println("爬虫:"+imgUrl);
                    downImages("src/爬虫",imgUrl);

                }
            }

    }

下载图片到本地的方法:

 /**
     * 下载图片到指定目录
     *
     * @param filePath 文件路径
     * @param imgUrl   图片URL
     */
    public static void downImages(String filePath, String imgUrl) {
        // 若指定文件夹没有,则先创建
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 截取图片文件名
        String fileName = imgUrl.substring(imgUrl.lastIndexOf('/') + 1, imgUrl.length());

        try {
            // 文件名里面可能有中文或者空格,所以这里要进行处理。但空格又会被URLEncoder转义为加号
            String urlTail = URLEncoder.encode(fileName, "UTF-8");
            // 因此要将加号转化为UTF-8格式的%20
            imgUrl = imgUrl.substring(0, imgUrl.lastIndexOf('/') + 1) + urlTail.replaceAll("\\+", "\\%20");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 写出的路径
        File file = new File(filePath + File.separator + fileName);

        try {
            // 获取图片URL
            URL url = new URL(imgUrl);
            // 获得连接
            URLConnection connection = url.openConnection();
            // 设置10秒的相应时间
            connection.setConnectTimeout(10 * 1000);
            // 获得输入流
            InputStream in = connection.getInputStream();
            // 获得输出流
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
            // 构建缓冲区
            byte[] buf = new byte[1024];
            int size;
            // 写入到文件
            while (-1 != (size = in.read(buf))) {
                out.write(buf, 0, size);
            }
            out.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

好吧 ,jsoup 是一款 Java 的 HTML 解析器,可直接解析某个 URL 地址、HTML 文本内容。它提供了一套非常省力的 API,可通过 DOM,CSS 以及类似于 jQuery 的操作方法来取出和操作数据。
jsoup 可以从包括字符串、URL 地址以及本地文件来加载 HTML 文档,并生成 Document 对象实例。
执行结果:


爬虫执行结果.png
上一篇下一篇

猜你喜欢

热点阅读