获取天气网地区-代码映射表

万年历api无法建立连接了,不知道为什么(XvX),于是想换一个api给机器人查天气

注意

程序编写于2022/09/28,注意代码的时效性

代码

最终格式为dict[地区名, 地区代码], 用pickle库二进制存入文件stations.silksINFn

请求天气的链接形如:http://t.weather.sojson.com/api/weather/city/101010100

import aiohttp
import asyncio
import json
import pickle

SEMAPHORE = 8

async def get_provinces_code() -> dict[str, str]:
    URL = 'http://www.weather.com.cn/data/city3jdata/china.html'
    async with semaphore:
        async with session.get(URL) as res:
            return json.loads(await res.text())

async def get_cities_code(province_code: str) -> tuple[str, dict[str, str]]:
    URL = 'http://www.weather.com.cn/data/city3jdata/provshi/{}.html'.format(province_code)
    async with semaphore:
        async with session.get(URL) as res:
            return province_code, json.loads(await res.text())

async def get_stations_code(city_code: str) -> tuple[str, dict[str, str]]:
    URL = 'http://www.weather.com.cn/data/city3jdata/station/{}.html'.format(city_code)
    async with semaphore:
        async with session.get(URL) as res:
            return city_code, json.loads(await res.text())

async def query():
    global session, semaphore
    session = aiohttp.ClientSession()
    semaphore = asyncio.Semaphore(SEMAPHORE)

    provinces_dict: dict[str, str] = await get_provinces_code()

    tasks: list[asyncio.Task[tuple[str, dict[str, str]]]] = []
    for code, province in provinces_dict.items():
        tasks.append(asyncio.ensure_future(get_cities_code(code)))
    await asyncio.wait(tasks)

    lst: list[str] = []
    for task in tasks:
        province_code, cities_dict = task.result()
        for code, city in cities_dict.items():
            lst.append(province_code + code)

    tasks = [asyncio.ensure_future(get_stations_code(each)) for each in lst]
    await asyncio.wait(tasks)

    final_dict: dict[str, str] = {}
    for task in tasks:
        city_code, stations_dict = task.result()
        for code, station in stations_dict.items():
            final_dict[station] = city_code + code
    
    with open('stations.silksINFn', 'wb') as f:
        pickle.dump(final_dict, f)

def main():
    global loop

    loop = asyncio.get_event_loop()
    loop.run_until_complete(query())

    session.close()

if __name__ == '__main__':
    main()


# http://t.weather.sojson.com/api/weather/city/101010100

其他

个人博客地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值