xiepufeng
7 months ago
2 changed files with 105 additions and 1 deletions
@ -0,0 +1,97 @@ |
|||
package com.zc.business.controller; |
|||
|
|||
import com.alibaba.fastjson.JSONArray; |
|||
import com.alibaba.fastjson.JSONObject; |
|||
import com.ruoyi.common.core.domain.AjaxResult; |
|||
import com.zc.common.core.httpclient.OkHttp; |
|||
import com.zc.common.core.httpclient.exception.HttpException; |
|||
import io.swagger.annotations.Api; |
|||
import io.swagger.annotations.ApiOperation; |
|||
import okhttp3.Response; |
|||
import org.jsoup.Jsoup; |
|||
import org.jsoup.nodes.Document; |
|||
import org.jsoup.nodes.Element; |
|||
import org.jsoup.select.Elements; |
|||
import org.springframework.web.bind.annotation.*; |
|||
|
|||
import java.io.IOException; |
|||
|
|||
/** |
|||
* 全国气象数据 |
|||
* |
|||
* @author xiepufeng |
|||
*/ |
|||
@Api(tags = "全国气象数据") |
|||
@RestController |
|||
@RequestMapping("/business/nmc") |
|||
public class DcNmcController { |
|||
|
|||
/** |
|||
* 雷达数据 |
|||
*/ |
|||
@ApiOperation("雷达数据") |
|||
@GetMapping("/radar") |
|||
public AjaxResult radar() throws HttpException, IOException { |
|||
|
|||
OkHttp okHttp = new OkHttp(); |
|||
Response response // 请求响应
|
|||
= okHttp |
|||
.url("http://www.nmc.cn/publish/radar/chinaall.html") // 请求地址
|
|||
.get(); // 请求方法
|
|||
|
|||
String html = response.body().string(); |
|||
|
|||
return AjaxResult.success(parseHtmlContent(html)); |
|||
} |
|||
|
|||
|
|||
/** |
|||
* 解析HTML内容,提取特定标签下的数据。 |
|||
* |
|||
* @param htmlContent 要解析的HTML字符串。 |
|||
* @return 返回一个JSONArray对象,包含解析得到的数据项。如果无法找到指定内容或解析失败,则返回空数组。 |
|||
*/ |
|||
private static JSONArray parseHtmlContent(String htmlContent) { |
|||
// 使用Jsoup解析HTML字符串
|
|||
Document doc = Jsoup.parse(htmlContent, "UTF-8"); |
|||
|
|||
// 尝试获取指定ID的元素
|
|||
Element tabContent = doc.getElementById("myTabContent"); |
|||
if (tabContent == null) { |
|||
// 如果找不到指定ID的元素,直接返回空数组
|
|||
return new JSONArray(); |
|||
} |
|||
|
|||
// 获取目标元素列表
|
|||
Elements targetElements = tabContent.child(0).child(0).children(); |
|||
|
|||
// 如果目标元素列表为空,同样返回空数组
|
|||
if (targetElements.isEmpty()) { |
|||
return new JSONArray(); |
|||
} |
|||
|
|||
// 初始化结果数组
|
|||
JSONArray jsonArray = new JSONArray(); |
|||
|
|||
// 遍历目标元素列表,提取每项数据
|
|||
for (Element targetElement : targetElements) { |
|||
// 提取"data-img"和"data-time"属性值
|
|||
String dataImg = targetElement.attr("data-img"); |
|||
String dataTime = targetElement.attr("data-time"); |
|||
|
|||
// 创建JSONObject,将提取到的数据项添加进去
|
|||
JSONObject jsonObject = new JSONObject(); |
|||
jsonObject.put("img", dataImg); |
|||
jsonObject.put("time", dataTime); |
|||
|
|||
// 将JSONObject添加到结果数组
|
|||
jsonArray.add(jsonObject); |
|||
} |
|||
|
|||
// 返回填充好的结果数组
|
|||
return jsonArray; |
|||
} |
|||
|
|||
|
|||
|
|||
} |
Loading…
Reference in new issue