• Java爬虫实战——利用jsoup爬取网页资源


    Jsoup简介

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

    上面的介绍,最关键就是jsoup是一款Java的HTML解析器,那么我们可以理解,通过它提供的API,我们可以像使用jQuery或者WebDriver一样去查找、定位甚至操作各种元素标签了。

    Jsoup API

    官网地址https://jsoup.org****
    java项目对应的jsoup包https://jsoup.org/download,使用jar或maven、gradle可按照需要自选。
    API 文档:https://jsoup.org/apidocs/index.html
     

    实践

    1.网页分析

    获取百度首页-推荐中图片

    2.编码

    1.新建java- maven项目,在pom.xml加上jsoup的依赖

        <dependency>
          <groupId>org.jsoup</groupId>
          <artifactId>jsoup</artifactId>
          <version>1.11.3</version>
        </dependency>

    2.新建测试类

    package com.test;
    
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    import org.jsoup.select.Elements;
    
    import java.io.*;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.URLEncoder;
    
    public class App
    {
        public static void main( String[] args )
        {
            String url = "https://www.baidu.com/";
            try{
                //从url加载html
                Document document = Jsoup.connect(url).get();
                //爬取title
                String title = document.title();
                System.out.println("标题:"+title);
                //爬取图片
                Elements imgs = document.getElementsByTag("img");
                System.out.println("开始下载");
                // 遍历img标签并获得src的属性
                for (Element element : imgs) {
                    //获取每个img标签URL "abs:"表示绝对路径
                    String imgSrc = element.attr("abs:src");
                    // 打印URL
                    System.out.println(imgSrc);
                    //下载图片到本地
                    downImages("e:/img", imgSrc);
                }
                System.out.println("下载完成");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        /**
         * 下载图片到指定目录
         *
         * @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转义为加号
                if(fileName.isEmpty()||fileName!=null){
                    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();
            }
    
        }
    }
  • 相关阅读:
    python3.x元组打印错误 TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'
    LoRa---她的简介和她的专业术语
    单片机程序在内存和FLASH中的空间分配
    STM32烧录的常用方式
    【原创】MapReduce编程系列之表连接
    Maven基础配置—本地Maven配置
    Maven基础配置--nexus私服配置
    OSGI入门笔记
    Maven仓库搭建--nexus私服
    javascript基础 方法 函数 闭包 集合
  • 原文地址:https://www.cnblogs.com/mumuluo/p/16405293.html
Copyright © 2020-2023  润新知