简单Java爬虫案例-HttpClient4.X+Jsoup爬取-ikun-表情包

news/2024/7/19 10:42:48 标签: java, 网络爬虫, 爬虫

🐔🐔🐔作为一名真爱粉怎么能没有ikun的表情包?🐔🐔🐔

🍓使用到的技术

  • HttpClient4.x 也就是 org.apache.http.xxx 这个版本

  • Jsoup 1.15.3

坤图来源:斗图王

🍒主要思路

  • 借助HttpClient通过GET方法请求资源

  • 将返回的实体对象转为源码(html)

  • 使用Jsoup解析出源码中图片地址

  • 下载图片到本地

🍎

  • Target host is not specified [需要把文件地址写完整,URL地址必须加协议名称(http或https)]

🍇爬取流程

查看网页结构及编码

查看编码

查看网页结构

查看结构发现,我们可以用css选择器轻松解析出来

#post_container > div > li > div > a > img

  • # 代表id选择器

  • > 代表层级结构

编写请求和返回实体的代码

尽可能打包成方法,方便代码复用
java">java">public static HttpEntity getEntityByHttpGetMethod(String url) throws IOException {
        //生成GET请求对象
        HttpGet httpGet = new HttpGet(url);
        //执行请求并获得响应对象
        HttpResponse httpResponse = httpClient.execute(httpGet);
        //获得响应实体
        HttpEntity entity = httpResponse.getEntity();
        return entity;
    }

编写保存图片的代码

使用BufferedInputStream下载图片更好一些
java">java">public static void saveImg(String url,String savePath) throws IOException {
        //获取图片信息,做输出流
        InputStream in = getEntityByHttpGetMethod(url).getContent();
        //定义每次读取的最大值为 1KB
        byte[] buffer = new byte[1024];
        BufferedInputStream inputStream = new BufferedInputStream(in);
        int len = 0;
        //创建缓冲流
        FileOutputStream out = new FileOutputStream(new File(savePath));
        BufferedOutputStream outputStream = new BufferedOutputStream(out);
        //图片写入
        while ((len = inputStream.read(buffer,0,1024)) != -1){
            outputStream.write(buffer,0,len);
        }
        //关闭缓冲流资源
        inputStream.close();
        outputStream.close();
    }

🍈完整代码

java">java">package com.ikun;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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.URLDecoder;
import java.net.URLEncoder;

/**
 * 使用工具 - HttpClient 4.X
 * 下载图片
 */
public class CrawlerImg {
    private static HttpClient httpClient = HttpClients.custom().build();
    private static String savePath = "D:\\ikun\\";

    public static void main(String[] args) throws IOException {
        String url = "https://www.doutuwang.com/?s=%E8%94%A1%E5%BE%90%E5%9D%A4";
        //String url = "https://www.doutub.com/search/%E8%94%A1%E5%BE%90%E5%9D%A4/1";
        //获得响应对象
        HttpEntity httpEntity = getEntityByHttpGetMethod(url);
        String html = EntityUtils.toString(httpEntity,"utf-8");
        //生成 Document对象
        Document doc = Jsoup.parse(html);
        Elements elements = doc.select("#post_container > div > li > div > a > img");
        System.out.println("共发现资源数目 "+elements.size());
        //下载100张
        int count = 0;
        for (Element element : elements){
            //System.out.println(element.text());
            count++;
            String picUrl = element.attr("src");
            System.out.println(picUrl);

            if (picUrl.contains("gif")){
                saveImg(picUrl,savePath+"00"+count+".gif");
            }else {
                saveImg(picUrl,savePath+"00"+count+".jpg");
            }
            if (count==100){
                break;
            }
            System.out.println("已下载到"+savePath);
        }
        System.out.println("共下载"+count+"张");
    }
    public static HttpEntity getEntityByHttpGetMethod(String url) throws IOException {
        //生成GET请求对象
        HttpGet httpGet = new HttpGet(url);
        //执行请求并获得响应对象
        HttpResponse httpResponse = httpClient.execute(httpGet);
        //获得响应实体
        HttpEntity entity = httpResponse.getEntity();
        return entity;
    }
    public static void saveImg(String url,String savePath) throws IOException {
        //获取图片信息,做输出流
        InputStream in = getEntityByHttpGetMethod(url).getContent();
        //定义每次读取的最大值为 1KB
        byte[] buffer = new byte[1024];
        BufferedInputStream inputStream = new BufferedInputStream(in);
        int len = 0;
        //创建缓冲流
        FileOutputStream out = new FileOutputStream(new File(savePath));
        BufferedOutputStream outputStream = new BufferedOutputStream(out);
        //图片写入
        while ((len = inputStream.read(buffer,0,1024)) != -1){
            outputStream.write(buffer,0,len);
        }
        //关闭缓冲流资源
        inputStream.close();
        outputStream.close();
    }
}

http://www.niftyadmin.cn/n/176650.html

相关文章

PostgreSQL中json_build_object的用法

在 PostgreSQL 数据库中,有时我们需要将多个字段合并成一个 JSON 对象,并将其用于保存或传输数据。json_build_object 函数可用于将指定的键值对合并为一个 JSON 对象。该函数的语法如下: sql json_build_object(key text, value any [, ...]) 其中&a…

go-zero 基础 -- 框架设计

框架设计 1、api语法介绍 1.1 api示例 /*** api语法示例及语法说明*/// api语法版本 syntax "v1"// import literal import "foo.api"// import group import ("bar.api""foo/bar.api" ) info(author: "songmeizi"date…

146. LRU 缓存

146. LRU 缓存 请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。 实现 LRUCache 类: LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存 int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值&#xff…

利用@RequestBody和@ResponseBody处理参数校验

是的,今天继续聊RequestBody和ResponseBody。 上次通过RequestMapping注解了解到了RequestMappingHandlerMapping和RequestMappingHandlerAdaptor。 这两兄弟在处理请求的过程中,RequestMappingHandlerMapping帮忙做了url与方法的具体映射,R…

【免费教程】 HEC-RAS 在防洪评价中的应用

HEC-RAS河道水力分析模型———HEC-RAS是一个针对一维恒定/非恒定流的水力模型,主要用于明渠河道流动分析和洪泛平原区域的确定。模型所得结果可以用于洪水区域管理以及洪水安全研究分析,用以评价洪水淹没区域的范围及危害程度。如在进行河道整治以及新建桥梁等工程的时候,就要…

【Android笔记86】Android之视频播放VideoView和音效播放SoundPool

这篇文章,主要介绍Android之视频播放VideoView和音效播放SoundPool。 目录 一、VideoView播放视频 1.1、VideoView介绍 1.2、VideoView的使用 (1)效果演示

小菜鸟Python历险记:(第六集)

今天写的文章是记录我从零开始学习Python的全过程。在python中可以在方法中定义全局变量,是通过一个关键字global来实现的。在python中的globals()方法可以返回一个包含全局范围内所有变量的字典,其中键是变量名,值为变量值。当然在python中还…

看野火的视频,用正点原子的板子(STM32F4探索者)做ADC读取电压实验

1. 实验目的 使用STM32F4的ADC1通道5(PA5)来采样外部电压值(这里采样两个电压值TPAD(3.3v),GND(0v)),最后通过串口打印电压值。 2. 实验准备和流程 由上图可…