1. 程式人生 > >java爬蟲抓取資料,儲存為excel檔案

java爬蟲抓取資料,儲存為excel檔案

  1. 下載jsoup jar包和poi jar包

  2. City.java

package dataToExcel;

public class City {
    private String name;
    private String url;
    public City(String name, String url) {
        super();
        this.name = name;
        this.url = url;
    }
    public String getName() {
        return name;
    }
    public
void setName(String name) { this.name = name; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
  1. CitiesToExcel.java
package dataToExcel;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util
.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jsoup.Jsoup
; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class CitiesToExcel { /** * @Method Description 獲得一個List物件,其中的資料使用網路爬蟲從網站上爬取 * * */ public static List<City> getCityList() throws IOException{ List<City> cityList = new ArrayList<City>(); Document doc = Jsoup.connect("http://bus.aibang.com/cities-bus").get(); Elements uls = doc.getElementsByTag("ul"); Element ul = uls.get(1); Elements lis = ul.getElementsByTag("li"); for(int i = 0;i<lis.size();i++){ Element li = lis.get(i); Elements as = li.getElementsByTag("a"); for(int j = 0;j<as.size();j++){ Element a = as.get(j); String cityname = a.text(); String cityurl = a.attr("href"); cityList.add(new City(cityname,cityurl)); } } return cityList; } /** * @Method Description 將資料寫入一個excel表格 * */ public static void main(String[] args) throws IOException { //第一步 建立一個webbook 對應一個excel檔案 HSSFWorkbook wb = new HSSFWorkbook(); //第二步 在webbook中新增一個sheet,對應excel中的sheet HSSFSheet sheet = wb.createSheet("表一"); //第三步 在sheet中新增表頭第0行 注意老版本poi對Excel的行數列數有限制short HSSFRow row = sheet.createRow(0); // 第四步,建立單元格,並設定值表頭 設定表頭居中 HSSFCellStyle style =wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //建立一個居中格式 HSSFCell cell1 = row.createCell(0); cell1.setCellValue("城市名"); cell1.setCellStyle(style); HSSFCell cell2 = row.createCell(1); cell2.setCellValue("URL"); cell2.setCellStyle(style); //第五步 寫入資料 從網路中爬取下來 List<City> list = getCityList(); for(int i = 0;i<list.size();i++){ row = sheet.createRow(i+1); //第四步 建立單元格 並設定值 row.createCell(0).setCellValue(list.get(i).getName()); row.createCell(1).setCellValue(list.get(i).getUrl()); } //第六步 將檔案儲存到指定位置 try{ FileOutputStream fos = new FileOutputStream("city_url.xls"); wb.write(fos); fos.flush(); fos.close(); }catch(Exception e){ e.printStackTrace(); } } }