Skip to content

Instantly share code, notes, and snippets.

@rangercyh
Last active March 20, 2023 08:33
Show Gist options
  • Save rangercyh/8119918 to your computer and use it in GitHub Desktop.
Save rangercyh/8119918 to your computer and use it in GitHub Desktop.
get weather api from china weather web
local http = require "socket.http"
local json = require "json"
local pfile = io.open("province", "w")
local cfile = io.open("city", "w")
local dfile = io.open("district", "w")
local provinces = {}
local citys = {}
local districts = {}
local RTprovinces = http.request("http://www.weather.com.cn/data/city3jdata/china.html")
local provinces = json.decode(RTprovinces)
for p_code, p_name in pairs(provinces) do
local citys_url = string.format("http://www.weather.com.cn/data/city3jdata/provshi/%s.html", p_code)
local RTcitys = http.request(citys_url)
if RTcitys then
citys[p_code] = json.decode(RTcitys)
end
pfile:write(string.format("%s, %s\n", p_code, p_name))
end
for p_code, tbCitys in pairs(citys) do
cfile:write(string.format("%s\n", provinces[p_code]))
for c_code, c_name in pairs(tbCitys) do
local city_key = p_code..c_code
local dicts_url = string.format("http://www.weather.com.cn/data/city3jdata/station/%s.html", city_key)
local RTdicts = http.request(dicts_url)
if RTdicts then
districts[city_key] = json.decode(RTdicts)
end
cfile:write(string.format("%s, %s\n", city_key, c_name))
end
end
for city_key, tbDicts in pairs(districts) do
local pcode = string.sub(city_key, 1, 5)
local ccode = string.sub(city_key, -2)
dfile:write(string.format("%s, %s\n", provinces[pcode], citys[pcode][ccode]))
for dcode, dname in pairs(tbDicts) do
dfile:write(string.format("%s, %s\n", city_key..dcode, dname))
end
end
pfile:close()
cfile:close()
dfile:close()
local file = io.open("district", "r")
local output = io.open("weather_city", "w")
output:write("<?php"..'\n')
while 1 do
local line = file:read("*l")
if line then
local city_code = string.sub(line, 1, string.find(line, ",") - 1)
local city_name = string.sub(line, string.find(line, ",") + 2, -1)
if tonumber(city_code) then
local str = string.format("$weather_city['%s'] = \"%s\";", city_name, city_code)
output:write(str..'\n')
end
else
break
end
end
output:write("?>")
file:close()
output:close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment