提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
背景
作为一名新时代的农民工,应该学会根据历史气温来决策农业行为。本程序旨在帮助那些需要采集包括但不限于天气信息数据的农户。
一. 找采集对象
我是以如下图网站作为采集对象,网址就不发了
二.获取历史天气对应的后台接口
1. 打开浏览器的调试模式,并点击获取历史天气相关的按钮
这里已经看到了他的后台数据接口了
2. 将后台接口拷贝出来,然后放入浏览器访问这个接口
结果如图,这里咱们已经确信他就是后台数据接口
如果看不懂是什么数据,没关系,这是因为这个是字节编码,咱们来对他解码看看。
这下清晰了吧。
3. 把返回的数据和解码后的数据分别保存一份
3.1 保存返回数据是我们可以用它来调试我们的程序,从而减少调试对于别人网站的依赖,等调试功能没有问题了,再去访问别人网站,采集数据的时候应该尽量少干扰别人的网站。
3.2 保存解码后的数据是我们需要分析如何解析他。
如图,可见,这个接口返回的数据是 html的标签,其中我们所要的数据主要是在这个 table标签中
4. 把咱们获取数据的URL进行解码分析传参
如图,对于我来说,获取历史数据的时候地区已经选择好了,所以参数我只需要改变年月就可以了
三. 制定开发策略
1. 我的策略如下
1.1 http api 接口,获取网站返回的数据
1.2 json解析返回的数据,拿到data里面的内容
1.3 使用Jsoup对data中的数据进行解析,获取表格具体数据条
1.4 将解析的数据存入Excel文档中
1.5 注意的地方:注意频率,因此每采集一条让程序睡个1秒,呵护下别人的网站
2. 程序依赖
<dependencies>
<!-- http 请求需要用到 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!-- json解析需要用到 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
<!-- 解析html标签需要用到 -->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
<!-- 写Excel文件需要用到 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.10</version>
</dependency>
<!-- 写Excel文件需要用到 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<!-- 一些文件操作要用到 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
3. 核心代码(如需要完整代码请联系)
String url = String.format("https://xxxxxx?date[year]=%d&date[month]=%d", year, month);//网址已经做过处理需要替换成你自己的地址
String body = client.getForEntity(url, String.class).getBody();
Thread.sleep(1000);
if(body != null)
{
JSONObject retObj = JSONObject.parseObject(body);
String table_data = retObj.get("data").toString();
Document doc = Jsoup.parse(table_data);
Elements rows = doc.select("table[class=history-table]").get(0).select("tr");
Elements cols = doc.select("table[class=history-table]").get(0).select("th");
if (rows.size() == 1) {
System.out.println("没有结果");
}else {
for(int i=1;i<rows.size();i++)
{
System.out.println("-----------------------------------------------------------------");
Element row = rows.get(i);
HSSFRow nextrow=sheet.createRow(nTotalRows++);
for (int j = 0; j < cols.size();j++)
{
System.out.println(cols.get(j).text() + ":" + row.select("td").get(j).text());
HSSFCell cell2=nextrow.createCell(j);
cell2.setCellValue(row.select("td").get(j).text());
}
System.out.println("-----------------------------------------------------------------");
}
}
}
4. 结果截图
5. 源码路径
点击下载:使用java程序采集地区历史天气源码