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);
}
}
結果展示: