天天看點

Java實作爬取京東手機資料

最近看了某馬的Java爬蟲視訊,看完後自己上手操作了下,基本達到了爬資料的要求,HTML頁面源碼也剛好複習了下,之前釋出兩篇關于簡單爬蟲的文章,也剛好用得上。項目沒什麼太難的地方,就是考驗你對HTML源碼的解析,層層解析,同标簽選擇器seletor進行元素篩選,再結合HttpCLient技術,成功把手機資料爬取下來。

一、項目Maven環境配置

1、配置SpringBoot

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
</parent>           

複制

2、pom檔案配置相關Jar包

<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>           

複制

3、添加配置檔案(放在resource檔案夾)

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/crawler
spring.datasource.username=root
spring.datasource.password=root

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

複制

二、相關類

POJO類

@Entity
@Table(name = "jd_item")
public class Item {
    //主鍵
    @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;

	...	... 	//  省略getter/setter、toString() 方法
}           

複制

Dao接口

public interface ItemDao extends JpaRepository<Item,Long> 	{}           

複制

業務層

public interface ItemService {

//根據條件查詢資料
public List<Item> findAll(Item item);

//儲存資料
public void save(Item item);

}           

複制

@Service
public class ItemServiceImpl implements ItemService {

@Autowired
private ItemDao itemDao;

@Override
public List<Item> findAll(Item item) {
    Example example = Example.of(item);
    List list = this.itemDao.findAll(example);
    return list;
}

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

複制

HttpClientUtils工具類(用來建立和銷毀HttpClient連接配接的連接配接池)

@Component
public class HttpUtils {

   private PoolingHttpClientConnectionManager cm;

    public HttpUtils() {
        this.cm = new PoolingHttpClientConnectionManager();

        //    設定最大連接配接數
        cm.setMaxTotal(100);
        //    設定每個主機的并發數
        cm.setDefaultMaxPerRoute(10);
    }

    /**
     * 根據請求位址下載下傳頁面資料
     * @param url
     * @return 頁面資料
     */
    public String doGetHtml(String url) {
    
        // 擷取HttpClient對象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        // 聲明httpGet請求對象
        HttpGet httpGet = new HttpGet(url);
        // 設定請求參數RequestConfig
        httpGet.setConfig(this.getConfig());

        // 浏覽器表示
        httpGet.addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
        // 傳輸的類型
        httpGet.addHeader("Cookie","Cookie位址");  //Cookie位址是你搜尋過後,開發者工具裡面的request Header位址,這裡太長了省略不寫
        
		//	上述兩行關于浏覽的代碼,是表示聲明你是正常的方式通路該網頁(可以了解為登入後正常通路)

		CloseableHttpResponse response = null;
        try {
            //  使用HttpClient發起請求,擷取響應
            response = httpClient.execute(httpGet);
            //  解析響應,傳回結果
            if (response.getStatusLine().getStatusCode()==200){
                //  判斷響應Entity是否不為空,如果不為空就可以使用EntityUtils
                if (response.getEntity() !=null){
                    String content = EntityUtils.toString(response.getEntity(), "utf8");
                    return content;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    // 關閉連接配接
                    response.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 下載下傳圖檔
     * @param url
     * @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());
        
        CloseableHttpResponse response = null;

        try {
            //  使用HttpClient發起請求,擷取響應
            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;
                    //  下載下傳圖檔
                    //  聲明 OutPutStream
                    OutputStream out = new FileOutputStream(new File("C:\\Users\\Desktop\\images\\"+picName));
                    response.getEntity().writeTo(out);
                    //  傳回圖檔名稱
                    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;
    }
}           

複制

ItemTask 任務類

@Component
public class ItemTask {

@Autowired
private HttpUtils httpUtils;

@Autowired
private ItemService itemService;

private static final ObjectMapper MAPPER = new ObjectMapper();

    //  當下載下傳任務完成後,間隔多長時間進行下一次的任務
    @Scheduled(fixedDelay =1000*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=1&click=0&page=";

        //  周遊頁面對手機的搜尋進行周遊結果
        for (int i = 1; i < 10; i=i+2) {
            String html = this.httpUtils.doGetHtml(url+i);
            //  解析頁面,擷取商品資料并存儲
            this.parse(html);
        }
        System.out.println("手機資料抓取完成!!!");
    }

    /**
     * 解析頁面,擷取商品資料并存儲
     * @param html
     */
    private void parse(String html) throws Exception {
        //  解析HTML擷取Document
        Document doc = Jsoup.parse(html);
        //  擷取spu
        Elements spuEles = doc.select("div#J_goodsList > ul > li");
        //  周遊擷取spu資料
        for (Element spuEle : spuEles) {
            //  擷取spu
            long spu = Long.parseLong(spuEle.attr("data-spu"));
            //  擷取sku資訊
            Elements skuEles = spuEles.select("li.ps-item");
            for (Element skuEle : skuEles) {
                //  擷取sku
                long sku = Long.parseLong(skuEle.select("[data-sku]").attr("data-sku")); 
                //  根據sku查詢商品資料
                Item item = new Item();
                item.setSku(sku);
                List<Item> list = this.itemService.findAll(item);
                if (list.size()>0){
                    //如果商品存在,就進行下一個循環,該商品不儲存,因為已存在
                    continue;
                }
                //  設定商品的spu
                item.setSpu(spu);

                //  擷取商品的詳情資訊
                String itemUrl = "https://item.jd.com/"+sku+".html";
                item.setUrl(itemUrl);

                //  商品圖檔
                String picUrl = skuEle.select("img[data-sku]").first().attr("data-lazy-img");
                //	圖檔路徑可能會為空的情況
                if(!StringUtils.isNotBlank(picUrl)){
                    picUrl =skuEle.select("img[data-sku]").first().attr("data-lazy-img-slave");
                }
                picUrl ="https:"+picUrl.replace("/n9/","/n1/");	//	替換圖檔格式
                String picName = this.httpUtils.doGetImage(picUrl);
                item.setPic(picName);

                //  商品價格
                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(item.getUrl());
                String title = Jsoup.parse(itemInfo).select("#itemName").text();
                item.setTitle(title);

                //  商品建立時間
                item.setCreated(new Date());
                //  商品修改時間
                item.setUpdated(item.getCreated());
                
                //  儲存商品資料到資料庫中
                this.itemService.save(item);

            }
        }
    }

}           

複制

ItemTask 引導類

@SpringBootApplication
//設定開啟定時任務
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}           

複制

結果展示:

Java實作爬取京東手機資料
Java實作爬取京東手機資料