前言
本文不是爬虫项目,只是日常工作中遇到的一个小需求,其实数据的收集并不难,难得是数据的后期清洗和补充。
本文主要是调取12306和高德地图api和百度地图api获取结果后进行解析,直接看下边的代码
1、获取现有火车站的基本信息
public void b(){
String url = "https://kyfw.12306.cn/otn/resources/js/framework/station_name.js";
String connection = null;
try {
connection = HttpClientUtil.doGet(url, null);
// System.out.println(connection);
String[] traiNameGroup = connection.split("@");
for (int i = 0; i < traiNameGroup.length; i++) {
String[] split = traiNameGroup[i].split("\\|");
TrainInfo trainInfo = new TrainInfo();
if (split.length>2){
updateMapper.InsertName(split[1]);
/*
5个字段的插入
trainInfo.setBy1(split[0]);
trainInfo.setTname(split[1]);
trainInfo.setBy2(split[2]);
trainInfo.setBy3(split[3]);
trainInfo.setBy4(split[4]);
trainInfo.setXh(split[5]);
updateMapper.insertTrainName(trainInfo);
*/
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
因为这里我只需要火车站的名字,所以我只是解析获取的字段,如果你需要别的,也可以自己解析,直接在浏览器中点开链接就可以看到结果
https://kyfw.12306.cn/otn/resources/js/framework/station_name.js
2、根据名字的不同调用百度地图接口api
首先登陆百度地图api网站,登录后进入控制台,选择我的应用,创建web服务应用,这样就可以了,下面的ak,就是你访问的钥匙
这里我们可以看下百度地图的api文档
不理解的可以先看看文档,下面直接代码了,代码中有大量的try…catch保证程序的运行(有许多字段为空。数据残缺),因为只是为了更新字典表,所以本文代码格式有点乱【汗颜】,代码最后的sleep是为了减少并发,否则百度会给你报警,除非你是RMB玩家。代码粘贴复制,记住添加你的ak。
@Component
public class LocationServer {
@Autowired
UpdateMapper updateMapper;
public void a(){
//读取城市名 上一步的我们直接存入数据库中,打上标志,代表全文件
List<String> stringList = updateMapper.selectTrainCity();
for (String s : stringList) {
String url = "http://api.map.baidu.com/place/v2/search?query=火车站®ion="+s+"&extensions_adcode=true&output=json&ak=你的ak";
String connection = null;
try {
connection = HttpClientUtil.doGet(url, null);
// System.out.println(connection);
} catch (Exception e) {
e.printStackTrace();
}
//解析json
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(connection);
if (jsonObject == null){
continue;
}
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("results");
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonArray ==null){
continue;
}
//循环数组
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = null;
try {
if (jsonArray == null) {
continue;
}
jsonObject1 = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
String name = null;
try {
name = jsonObject1.getString