气象局地址:http://www.weather.com.cn/
从网站上分析出了两个地址:
1、市区列表:https://j.i8tq.com/weather2020/search/city.js
2、查询市区天气:http://d1.weather.com.cn/weather_index/101010100.html
那么根据市区名称遍历市区列表拿到编码,再用编码查询天气即可,代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://libs.baidu.com/jquery/1.9.1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" src="https://j.i8tq.com/weather2020/search/city.js"></script>
<title></title>
<script>
$(function() {
// getWeather('101210101');
$("#searchBtn").on("click", function(){
var city = $("#city").val();
if(city == ""){
return;
}
var areaId = getAreaId(city);
if(areaId != ""){
getWeather(areaId);
}
})
})
function getWeather(areaId) {
$.getScript("http://d1.weather.com.cn/weather_index/"+areaId+".html", function() {
var weatherJson = eval("cityDZ");
$("#result").val(JSON.stringify(weatherJson));
})
}
function getAreaId(areaName) {
var areaId = "";
for(var o in city_data){
for(var o1 in city_data[o]){
for(var o2 in city_data[o][o1]){
if(areaName == city_data[o][o1][o2]["NAMECN"]){
areaId = city_data[o][o1][o2]["AREAID"];
break;
}
}
}
}
return areaId;
}
</script>
</head>
<body>
<div>
<input type="text" id="city" placeholder="城市" />
<input type="button" id="searchBtn" value="查询天气"></input>
<br />
<textarea id="result" rows="5" cols="70" style="margin-top: 20px;"></textarea>
</div>
</body>
</html>