数据分析之Java抓取搜狗指数数据

在处理数据分析的时候,如果我们的数据来源于网页,则需要通过数据爬虫来实现将网页端的数据转化到本地存储,再进行分析。
在这篇文章中,我们将介绍一步步介绍从搜狗指数下载数据到Excel文件中。

分析搜狗指数网页

想要从一个网页下载数据,首先需要了解网页中的数据结构,这里以宠物搜索数据为例。

对于这样的页面数据

搜狗指数-宠物

通过F12进入到网页的源代码,可以看到

搜狗指数-宠物-源码

接下来,我们就是想办法将在script标签中的数据导出来

通过Java将搜狗指数数据保存到Excel中

  • 通过Jsoup获取页面源码
    1
    2
    Document doc = Jsoup.connect(url).get();
    String script = doc.selectFirst("script").html();
  • 处理script标签提取json数据到对象集合
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    Pattern p = Pattern.compile("root.SG.wholedata = (.*)", Pattern.MULTILINE);
    Matcher matcher = p.matcher(script);
    String wholedata = "";
    while(matcher.find()) {
    wholedata = matcher.group(1);
    }
    ObjectMapper objectMapper = new ObjectMapper();
    SougouData sougouData = objectMapper.readValue(wholedata, SougouData.class);
    for (Pv pv : sougouData.pvList.get(0)) {
    IndexTrend indexTrend = new IndexTrend();
    indexTrend.date = pv.date;
    indexTrend.PV = pv.pv;
    indexTrends.add(indexTrend);
    }
  • 保存对象到Excel文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public void SaveToExcel(Set<IndexTrend> indexTrends) throws IOException {
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Pet");
    int rowNum = 0;
    for (IndexTrend indexTrend : indexTrends) {
    Row row = sheet.createRow(rowNum++);
    Cell date = row.createCell(0);
    Cell pv = row.createCell(1);
    CellStyle cellStyle = workbook.createCellStyle();
    CreationHelper createHelper = workbook.getCreationHelper();
    cellStyle.setDataFormat(
    createHelper.createDataFormat().getFormat("yyyy-MM-dd"));
    date.setCellValue(indexTrend.date);
    date.setCellStyle(cellStyle);
    pv.setCellValue(indexTrend.PV);
    }
    FileOutputStream outputStream = new FileOutputStream("./Download Sougou To Excel/petdata.xlsx");
    workbook.write(outputStream);
    workbook.close();
    }