java簡單實現爬蟲、jsoup實現網頁抓取、POI實現數據導出Excel

概要:

     使用java實現爬蟲,並且把數據保存到excel表中格式化保存;目標網站如下,爬取該網站的農產品價格!!!!


一、知識準備

jsoup:

jsoup 是一款 Java HTML 解析器,可直接解析某個 URL 地址、HTML 文本內容。它提供了一套非常省力的 API,可通過 DOMCSS 以及類似於 jQuery 的操作方法來取出和操作數據。

jsoup官網:http://jsoup.org

目前最新版本:jsoup-1.10.2.jar

 jsoup 的主要功能如下:

 1. 從一個 URL,文件或字符串中解析 HTML

2. 使用 DOM CSS 選擇器來查找、取出數據;

3. 可操作 HTML 元素、屬性、文本;

POI:

POI全稱 Poor Obfuscation Implementation,利用POI接口可以通過JAVA操作Microsoft office 套件工具的讀寫功能。官網:http://poi.apache.org POI支持office的所有版本。

二、maven工程的依賴jar準備

<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>
	<groupId>com.dark</groupId>
	<artifactId>reptile</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<dependencies>
	
	  <!--   jsoup和httpclient -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.5.3</version>
		</dependency>


		<dependency>
			<groupId>org.jsoup</groupId>
			<artifactId>jsoup</artifactId>
			<version>1.10.2</version>
		</dependency>


   
       <!--   poi的依賴包 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.16</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.16</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-excelant</artifactId>
			<version>3.16</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-examples</artifactId>
			<version>3.16</version>
		</dependency>
	</dependencies>

</project>

三、代碼實現

3.1、創建product對象實現,數據的接收和過渡;

package com.dark.pojo;
/**  作者:darkjazz 
*    日期:2018年3月22日 下午7:32:03
*/
public class Product {
     private String productName;
     private String lowerPrice;
     private String averagePrice;
     private String maxPrice;
     //規格
     private String specs;
     //單位
     private String unit;
     //發佈日期
     private String date;

	@Override
	public String toString() {
		return "Product [productName=" + productName + ", lowerPrice=" + lowerPrice + ", averagePrice=" + averagePrice
				+ ", maxPrice=" + maxPrice + ", specs=" + specs + ", unit=" + unit + ", date=" + date + "]";
	}

	public String getProductName() {
		return productName;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public String getLowerPrice() {
		return lowerPrice;
	}

	public void setLowerPrice(String lowerPrice) {
		this.lowerPrice = lowerPrice;
	}

	public String getAveragePrice() {
		return averagePrice;
	}

	public void setAveragePrice(String averagePrice) {
		this.averagePrice = averagePrice;
	}

	public String getMaxPrice() {
		return maxPrice;
	}

	public void setMaxPrice(String maxPrice) {
		this.maxPrice = maxPrice;
	}

	public String getSpecs() {
		return specs;
	}

	public void setSpecs(String specs) {
		this.specs = specs;
	}

	public String getUnit() {
		return unit;
	}

	public void setUnit(String unit) {
		this.unit = unit;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}
	
}

3.2、使用poi的excel操作的方法,把下一步爬取到的數據保存到本地硬盤的excel表中

package com.dark.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.dark.pojo.Product;

/**  作者:darkjazz
*    日期:2018年3月22日 下午8:00:33
*/
public class POItoExcel {
     public static void main(String[] args) {
		
	}
	public static void toExcel(List<Product> list) throws FileNotFoundException, IOException{
		 
        //新建文檔   
        XSSFWorkbook workBook=new XSSFWorkbook();
        
        //創建表
        XSSFSheet sheet=workBook.createSheet();
        
           //合併標的標題
      		CellRangeAddress cra=new CellRangeAddress(0,1, 0, 6);
      		sheet.addMergedRegion(cra);
      		//顯示的文本爲左上角的內容
      		Row row2=sheet.createRow(0);
      		Cell cell=row2.createCell(0);
      		cell.setCellValue("商品價格表");
      		//設置單元格的格式
      		CellStyle cs=workBook.createCellStyle();
      		cs.setAlignment(HorizontalAlignment.CENTER);
      		cs.setVerticalAlignment(VerticalAlignment.CENTER);
      		cs.setFillBackgroundColor((short) 59);
      	        cell.setCellStyle(cs);
      		//表頭
      		Row row=sheet.createRow(2);
      		
      		Cell cell11=row.createCell(0);
      		cell11.setCellValue("品名");
      		Cell cell22=row.createCell(1);
      		cell22.setCellValue("最低價");
      		Cell cell33=row.createCell(2);
      		cell33.setCellValue("平均價");
      		Cell cell44=row.createCell(3);
      		cell44.setCellValue("最高價");
      		Cell cell55=row.createCell(4);
      		cell55.setCellValue("規格");
      		Cell cell66=row.createCell(5);
      		cell66.setCellValue("單位");
      		Cell cell77=row.createCell(6);
      		cell77.setCellValue("發佈日期");
      	    //表中的數據

        for(int i=0;i<list.size();i++){
        //創建行
        XSSFRow row4=sheet.createRow(i+3);
  
        //創建單元格
        XSSFCell cell1=row4.createCell(0);
        XSSFCell cell2=row4.createCell(1);
        XSSFCell cell3=row4.createCell(2);
        XSSFCell cell4=row4.createCell(3);
        XSSFCell cell5=row4.createCell(4);
        XSSFCell cell6=row4.createCell(5);
        XSSFCell cell7=row4.createCell(6);
        	//在單元格中寫入數據
        cell1.setCellValue(list.get(i).getProductName());
        cell2.setCellValue(list.get(i).getLowerPrice());
        cell3.setCellValue(list.get(i).getAveragePrice());
        cell4.setCellValue(list.get(i).getMaxPrice());
        cell5.setCellValue(list.get(i).getSpecs());
        cell6.setCellValue(list.get(i).getUnit());
        cell7.setCellValue(list.get(i).getDate());
        }
         //把這個文檔寫入文件
        workBook.write(new FileOutputStream(new File("你的目標目錄"+\\product.xlsx")) );
        System.out.println("寫入excel完畢");
        //關閉流
        workBook.close();
		
	}
     
     
}

3.3、主方法,使用jsout實現爬蟲,並調用3.2中的方法實現寫入文件

package com.dark.reptile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.dark.pojo.Product;
import com.dark.util.POItoExcel;

/**  作者:darkjazz 
*    日期:2018年3月22日 下午7:11:20
*/
public class Reptile {
       public static void main(String[] args) throws FileNotFoundException, IOException {
    	   List<Product> list=getInfor("http://www.xinfadi.com.cn/marketanalysis/1/list/1.shtml", 1000);
    	   POItoExcel.toExcel(list);
	}
	
       //可以指定網址,並且按照需求爬取前多少頁的數據
       public static List<Product> getInfor(String url,int maxPage){
    	   List<Product> proList=new ArrayList<Product>();
    	   for(int i=2;i<=maxPage+1;i++){
    	      
    		 try {
    			
				Document doc=Jsoup.connect(url).get();
				Elements table=doc.select(".hq_table");
				Elements tbody=table.select("tbody");
				Elements trList=tbody.select("tr");
				trList.remove(0);
				for(Element tr:trList){
					Elements tdList=tr.select("td");
					Product product=new Product();
					product.setProductName(tdList.get(0).html().toString());
					product.setLowerPrice(tdList.get(1).html().toString());
					product.setAveragePrice(tdList.get(2).html().toString());
					product.setMaxPrice(tdList.get(3).html().toString());
					product.setSpecs(tdList.get(4).html().toString());
					product.setUnit(tdList.get(5).html().toString());
					product.setDate(tdList.get(6).html().toString());
					/*System.out.println(product.toString());*/
					proList.add(product);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    
    	   url="http://www.xinfadi.com.cn/marketanalysis/1/list/"+i+".shtml";
    	   }
    	   System.out.println("爬取前"+maxPage+"成功");
		return proList;
    	   
       }
	
	
	
}

四、效果展示


本次爬取實現爬取1000頁數據的效果!!!!


五、源碼包

歡迎訪問我的github首頁獲取

博主的github地址,獲取當前項目源碼


完結、散花!!!!!



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章