springboot+jpa+jsoup+HttpClient实现爬取京东数据

pojo

package com.ccx.pojo;
import java.util.Date;
import javax.persistence.*;

//商品的实体类
@Entity
//数据库表名称
@Table(name = "jd_item")
public class Item {
    //主键
    //id增长策略
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    //标准商品单位(商品集合)
    private Long spu;
    //库存量单位(最小品类单元)
    private Long sku;
    //商品标题
    private String title;
    //商品价格
    private Double price;
    //商品图片
    private String pic;
    //商品详情地址
    private String url;
    //创建时间
    private Date created;
    //更新时间
    private Date updated;

    public Item() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long getSpu() {
        return spu;
    }

    public void setSpu(Long spu) {
        this.spu = spu;
    }

    public Long getSku() {
        return sku;
    }

    public void setSku(Long sku) {
        this.sku = sku;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getUpdated() {
        return updated;
    }

    public void setUpdated(Date updated) {
        this.updated = updated;
    }
}


resource

#DB Configuration
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/crawler?useUnicode=yes&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123

#JPA Configuration
spring.jpa.database=MySQL
spring.jpa.show-sql=true

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
    </parent>

    <groupId>com.zzdreamz</groupId>
    <artifactId>crawler-jd</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>

        <!--SpringMVC-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--SpringData Jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!--MySQL连接包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!--HttpClient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>

        <!--Jsoup-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.3</version>
        </dependency>

        <!--工具包-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>

    </dependencies>

</project>

ItemDao

package com.ccx.dao;

import com.ccx.pojo.Item;
import org.springframework.data.jpa.repository.JpaRepository;

public interface ItemDao extends JpaRepository<Item,Long>{

}

ItemService

package com.ccx.service;

import java.util.List;

import com.ccx.pojo.Item;

public interface ItemService {
    /**
     * 保存商品
     */
    public void save(Item item);

    /**
     * 查询商品是否存在
     */
    public List<Item> findAll(Item item);

}

ItemServiceImpl

package com.ccx.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import com.ccx.dao.ItemDao;
import com.ccx.pojo.Item;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemDao itemDao;

    @Override
    @Transactional
    public void save(Item item) {
        this.itemDao.save(item);
    }

    @Override
    public List<Item> findAll(Item item) {

        //声明查询条件
        Example<Item> example = Example.of(item);
        //根据条件进行查询数据
        List<Item> list = this.itemDao.findAll(example);

        return list;
    }
}

itemtask

package com.ccx.task;

import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

import com.ccx.pojo.Item;
import com.ccx.service.ItemService;
import com.ccx.util.HttpUtils;

@Component
public class ItemTask {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private ItemService itemService;

    private static final ObjectMapper MAPPER = new ObjectMapper();

    //当下载任务完成后,间隔多长时间进行下一次的任务
    //查看搜索页面的地址,会发现有page参数来实现页码的控制
    @Scheduled(fixedDelay = 100*1000)
    public void itemTask() throws Exception {
        String url = "https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc" +
                "=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&s=57&click=0&page=";

        //按照页码对手机的搜索结果进行遍历
        for (int i = 3; i < 10; i +=2) {
            String html = httpUtils.doGetHtml(url + i);

            //解析页面,获取商品数据并储存
            this.parse(html);

        }

        System.out.println("手机数据抓取成功");
    }

    //解析页面,获取商品数据并储存
    private void parse(String html) throws Exception {
        //解析html获取Document对象
        Document doc = Jsoup.parse(html);

        Elements spuEles = doc.select("div#J_goodsList > ul > li");
        for (Element spuEle : spuEles) {
            if ( "".equals(spuEle.attr("data-spu"))) {
                continue;
            }
            //获取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));

            //获取sku集合
            Elements skuElems = spuEle.select("li.ps-item");

            for (Element skuElem : skuElems) {
                //获取sku
                long sku = Long.parseLong(skuElem.select("[data-sku]").attr("data-sku"));
                //根据sku查询商品数据
                Item item = new Item();

                item.setSku(sku);
                //设置商品的spu
                item.setSpu(spu);

                List<Item> list = this.itemService.findAll(item);

               if (list.size() > 0) {
                    //如果商品存在,就进行下一个循环,该商品不保存,因为已存在
                    continue;
                }



                //获取商品的详情url
                String itemUrl = "https://item.jd.com/"+sku+".html";
                item.setUrl(itemUrl);

                //获取商品图片
                String picUrlStr = skuElem.select("img[data-sku]").first().attr("data-lazy-img");
                //部分商品图片规则不一样,不想查日志找那部分不一样,就直接跳过了
                if (picUrlStr == null || "".equals(picUrlStr)) {
                    continue;
                }
                String picUrl = "https:" + picUrlStr;
                picUrl = picUrl.replace("/n9/","/n1/");
                String picName2 = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName2);

                //获取商品价格
                String priceJson = this.httpUtils.doGetHtml("https://p.3.cn/prices/mgets?skuIds=J_" + sku);
                double price = MAPPER.readTree(priceJson).get(0).get("p").asDouble();
                item.setPrice(price);


                //获取商品标题
                String itemInfo = this.httpUtils.doGetHtml(itemUrl);
                String title = Jsoup.parse(itemInfo).select("div.sku-name").text();
                item.setTitle(title);

                item.setCreated(new Date());
                item.setUpdated(item.getCreated());

                //保存商品到数据库中
                this.itemService.save(item);

            }
        }

    }
}

HttpUtils

package com.ccx.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
@Component
public class HttpUtils {

    //使用连接池管理
    private PoolingHttpClientConnectionManager cm;

    //初始化连接池
    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();

        //设置最大连接数
        this.cm.setMaxTotal(100);
        //设置每个主机的最大连接数
        this.cm.setDefaultMaxPerRoute(10);

    }

    //根据请求地址下载页面数据
    public String doGetHtml(String url) {
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //创建HttpGet请求对象,设置url地址
        HttpGet httpGet = new HttpGet(url);

        //设置请求信息
        httpGet.setConfig(this.getConfig());

        //程序访问京东的时候会报错说未登录,所以要先自己登录京东,获取到请求头中的User_Agent和Cookie
        //设置请求头
        httpGet.setHeader("自己的");
        httpGet.setHeader("自己的");


        //使用HttpClient发起请求,获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            //解析响应,返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空,如果不为空就可以使用EntityUtils
                if (response.getEntity() != null) {
                    String content = EntityUtils.toString(response.getEntity());
                    return content;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回空串
        return "";
    }



    //下载图片
    public String doGetImage(String url) {
        //获取HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();

        //创建HttpGet请求对象,设置url地址
        HttpGet httpGet = new HttpGet(url);

        //配置请求信息
        httpGet.setConfig(this.getConfig());

        //程序访问京东的时候会报错说未登录,所以要先自己登录京东,获取到请求头中的User_Agent和Cookie
        //设置请求头
        httpGet.setHeader("自己的");
        httpGet.setHeader("自己的");

        //使用HttpClient发起请求,获取响应
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);

            //解析响应,返回结果
            if (response.getStatusLine().getStatusCode() == 200) {
                //判断响应体Entity是否不为空,如果不为空就可以使用EntityUtils
                if (response.getEntity() != null) {
                    //下载图片
                    //获取图片的后缀
                    String extName = url.substring(url.lastIndexOf("."));

                    //创建图片名,重命名图片
                    String picName = UUID.randomUUID().toString() + extName;

                    //下载图片
                    //声明OutputString,指定图片保存地址
                    OutputStream outputStream = new FileOutputStream(new File("C:/Users/HP/Desktop/images/" + picName));
                    response.getEntity().writeTo(outputStream);

                    //返回图片名称
                    return picName;

                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭response
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //返回空串
        return "";
    }

    //配置请求的信息
    private RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(1000)    //创建链接的最长时间
                .setConnectionRequestTimeout(500)   //获取连接的最长时间
                .setSocketTimeout(10000)    //数据传输的最长时间
                .build();

        return config;
    }
}

在这里插入图片描述

运行结果
在这里插入图片描述

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值