java第一次简单实现爬虫

1、Games类
public class Games {
    public static String getHtmlResourceByURL(String url,String encoding)
    {
        //声明一个存储网页源代码的容器——字符缓冲区
        StringBuffer buffer=new StringBuffer();

        //注意涉及流的地方要给其一个初始值
        URL urlObj=null;
        URLConnection uc=null;
        InputStreamReader in=null;
        BufferedReader reader=null;

        //因为存在网络等原因的连接失败,所以要try,catch抛出异常
        try {
            //建立网络连接
            urlObj=new URL(url);
            //打开网络连接
            uc=urlObj.openConnection();
            //建立网络的输入流
            in=new InputStreamReader(uc.getInputStream(),encoding);
            //缓冲写入文件流
            reader=new BufferedReader(in);
            //临时变量
            String tempLine=null;
            //一行一行的读取文件流
            while((tempLine=reader.readLine())!=null)
            {
                //将数据放入缓冲区
                buffer.append(tempLine+"\n");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接超时!");
        }
        //随手关闭流
        finally{
            if(in !=null)
            {
                try
                {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.print("关闭出错");
                }
            }
        }
        //buffer(Stringbuffer类型转化为String类型)
        return buffer.toString();
    }


    /*
     * 根据一个图片URL地址,批量下载图片到服务器磁盘filePath
     * @param imgURL 要下载的图片服务器地址
     * @param filePath 下载保存图片地址
     */
    public static void downImages(String imgURL,String filePath)
    {
        //根据指定路径创建目录
        File parent = new File(filePath);
        //判断文件夹是否存在
        if(!parent.exists()){
            parent.mkdirs();
        }
        //获取图片名字,即截取图片路径最后一个/后面的内容
        String fileName=imgURL.substring(imgURL.lastIndexOf("/"));
        //获取文件的后缀名
        String imgType = imgURL.substring(imgURL.lastIndexOf(".")+1);
        try {
            //使用javaImageIO读取指定URL下的图片
            BufferedImage image = ImageIO.read(new URL(imgURL));
            System.out.println(fileName+","+imgType+","+image);
            //parent目录下创建指定文件名称文件file
            File  file = new File(parent,fileName);
            System.out.println(file.getAbsolutePath());
            ImageIO.write(image, imgType, file);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

2、DownGameController类抓取内容,创建jdbc连接存入数据库

public class DownGameController {

    private static void getInsert()
    {
        String imgSrc=null;
        String aHref=null;
        String aAlt=null;
        String divVideo=null;
        int lastPage;
        //获取源代码
        String htmlPageResource= Games.getHtmlResourceByURL("http://pubg.ali213.net/pubg/videolist/jxsp/","utf-8");
        System.out.println("源代码为:"+htmlPageResource);
        //解析源代码
        Document documentPage= Jsoup.parse(htmlPageResource);
        //抓取字段为末页的‘href’中的内容只取其中的数字并转化为int类型
        lastPage = Integer.parseInt(documentPage.getElementsByClass("lastPage").attr("href").replace("/pubg/videolist/jxsp/",""));
        System.out.println("末页的内容:" + lastPage);
        //根据末页的页数值循环抓取几次页面数据
        for (int i=1;i<=lastPage;i++) {
            System.out.println("" + i + "页开始!");
            //获取源代码
            String htmlResource= Games.getHtmlResourceByURL("http://pubg.ali213.net/pubg/videolist/jxsp/" + i,"utf-8");
            //解析源代码
            Document document= Jsoup.parse(htmlResource);
            //获取网页图片,视频,标题的集合
            Elements elements = document.getElementsByTag("a");

            for (Element element : elements) {
                //jsoupelementattrXX)的作用,根据属性取数据
                //获取资源相对地址
                aHref = element.attr("href");//获取视频
                aAlt = element.attr("alt");//获取标题
                imgSrc = element.getElementsByTag("img").attr("src");//获取图片
                if (imgSrc != "" && aHref.indexOf("http") < 0 && aHref.indexOf("html") > 0 && aAlt != "") {
                    System.out.println("下载视频地址:" + aHref);
                    String video = Games.getHtmlResourceByURL("http://pubg.ali213.net" + aHref, "utf-8");//获取点击视频后的源代码
                    Document document1 = Jsoup.parse(video);//解析源代码
                    divVideo = document1.getElementsByClass("video").toString();//获取class=“video”div内容
                    System.out.println("下载视频地址的DIV内容:" + divVideo);
                    System.out.println("对应标题:" + aAlt);
                    System.out.println("下载图片地址:" + imgSrc);
                    insert(divVideo,imgSrc,aAlt);//插入数据
                    System.out.println("成功");
                }
            }
        }
    }

    /*
    创建jdbc连接数据库
     */
    private static void insert(String content,String images,String title){
        Connection conn = null;
        Statement stmt = null;
        Date date = new java.util.Date();// 获取系统当前时间
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(date);// 将时间格式转换成符合Timestamp要求的格式.
        System.out.println(nowTime);
        try {
            //加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
            //创建连接对象
            conn= DriverManager.getConnection("数据库地址", "root", "1234");
            //创建sql执行对象
            stmt = conn.createStatement();
            //执行SQL语句
            stmt.executeUpdate("INSERT INTO 表名() values()");
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            try{
                if(stmt!=null){
                    stmt.close();
                    stmt=null;
                }
                if(conn!=null){
                    conn.close();
                    conn=null;
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args){
        getInsert();
    }

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值