需求分析
首先訪問京東,搜索手機,分析頁面,我們抓取以下商品數據:
商品圖片、價格、標題、商品詳情頁
SPU和SKU
除了以上四個屬性以外,我們發現上圖中的蘋果手機有四種產品,我們應該每一種都要抓取。那么這里就必須要了解spu和sku的概念。
SPU = Standard Product Unit (標准產品單位)
SPU是商品信息聚合的最小單位,是一組可復用、易檢索的標准化信息的集合,該集合描述了一個產品的特性。通俗點講,屬性值、特性相同的商品就可以稱為一個SPU。
例如上圖中的蘋果手機就是SPU,包括紅色、深灰色、金色、銀色
SKU=stock keeping unit(庫存量單位)
SKU即庫存進出計量的單位, 可以是以件、盒、托盤等為單位。SKU是物理上不可分割的最小存貨單元。在使用時要根據不同業態,不同管理模式來處理。在服裝、鞋類商品中使用最多最普遍。
例如上圖中的蘋果手機有幾個款式,紅色蘋果手機,就是一個sku
查看頁面的源碼也可以看出區別
開發准備
數據庫表分析
根據需求分析,我們創建的表如下:
CREATE TABLE `jd_item` (
`id` bigint(10) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`spu` bigint(15) DEFAULT NULL COMMENT '商品集合id',
`sku` bigint(15) DEFAULT NULL COMMENT '商品最小品類單元id',
`title` varchar(100) DEFAULT NULL COMMENT '商品標題',
`price` bigint(10) DEFAULT NULL COMMENT '商品價格',
`pic` varchar(200) DEFAULT NULL COMMENT '商品圖片',
`url` varchar(200) DEFAULT NULL COMMENT '商品詳情地址',
`created` datetime DEFAULT NULL COMMENT '創建時間',
`updated` datetime DEFAULT NULL COMMENT '更新時間',
PRIMARY KEY (`id`),
KEY `sku` (`sku`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='京東商品表';
添加依賴
使用Spring Boot+Spring Data JPA和定時任務進行開發,
需要創建Maven工程並添加以下依賴
<?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.0.2.RELEASE</version>
</parent>
<groupId>cn.itcast.crawler</groupId>
<artifactId>itcast-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>
添加配置文件
加入application.properties配置文件
#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
根據數據庫表,編寫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;
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;
}
}
編寫dao層
public interface ItemDao extends JpaRepository<Item,Long> {
}
編寫service服務層
ItemService接口如下:
public interface ItemService {
/** * 保存商品 * @param item */
public void save(Item item);
/** * 根據條件查詢商品 * @param item * @return */
public List<Item> findAll(Item item);
}
ItemServiceImpl 實現類如下:
@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;
}
}
編寫HttpUtils
@Component
public class HttpUtils {
private PoolingHttpClientConnectionManager cm;
public HttpUtils() {
this.cm = new PoolingHttpClientConnectionManager();
//設置最大連接數
this.cm.setMaxTotal(100);
//設置每個主機的最大連接數
this.cm.setDefaultMaxPerRoute(10);
}
/** * 根據請求地址下載頁面數據 * * @param url * @return 頁面數據 */
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());
CloseableHttpResponse response = null;
try {
//使用HttpClient發起請求,獲取響應
response = httpClient.execute(httpGet);
//解析響應,返回結果
if (response.getStatusLine().getStatusCode() == 200) {
//判斷響應體Entity是否不為空,如果不為空就可以使用EntityUtils
if (response.getEntity() != null) {
return EntityUtils.toString(response.getEntity(), "utf8");
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//關閉response
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//返回空串
return "";
}
/** * 下載圖片 * * @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是否不為空
if (response.getEntity() != null) {
//下載圖片
//獲取圖片的后綴
String extName = url.substring(url.lastIndexOf("."));
//創建圖片名,重命名圖片
String picName = UUID.randomUUID().toString() + extName;
//下載圖片
//聲明OutPutStream
OutputStream outputStream = new FileOutputStream(new File("C:\\Users\\86152\\Desktop\\image\\" +
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;
}
}
編寫ItemTask
@Component
public class ItemTask {
@Autowired
private HttpUtils httpUtils;
@Autowired
private ItemService itemService;
private static final ObjectMapper MAPPER = new ObjectMapper();
//當下載任務完成后,間隔多長時間進行下一次的任務。
@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&cid2=653&cid3=655&s=113&click=0&page=";
//按照頁面對手機的搜索結果進行遍歷解析
for (int i = 1; i < 10; i = 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);
//獲取spu信息
Elements spuEles = doc.select("div#J_goodsList > ul > li");
for (Element spuEle : spuEles) {
//獲取spu
long spu;
if("".equals(spuEle.attr("data-spu"))){
spu = 0L;
}else{
spu = Long.parseLong(spuEle.attr("data-spu"));
}
//獲取sku信息
Elements skuEles = spuEle.select("li.gl-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);
//獲取商品的詳情的url
String itemUrl = "https://item.jd.com/" + sku + ".html";
item.setUrl(itemUrl);
//獲取商品的圖片
String picUrl ="https:"+ skuEle.select("img[data-img]").first().attr("src");
String picName = this.httpUtils.doGetImage(picUrl);
item.setPic(picName);
//獲取商品的價格
String priceJson = skuEle.select(".p-price > strong > i").first().text();
double price = Double.parseDouble(priceJson);
item.setPrice(price);
//獲取商品的標題
String title = skuEle.select(".p-name > a > em").first().text();
item.setTitle(title);
item.setCreated(new Date());
item.setUpdated(item.getCreated());
//保存商品數據到數據庫中
this.itemService.save(item);
}
}
}
}
編寫啟動類
@SpringBootApplication
//使用定時任務,需要先開啟定時任務,需要添加注解
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}