WXGC-yang

获取全国省市区数据

起因

最近在做项目时需要用户选择配送地点,需要一个省市区的选择器,但是网上找了半天没有找到合适的数据,要么就是数据太久远,不全,要么就是要收费,还有些第三方api可以用,但是调用次数有限制等,想起之前高德有一个获取地图绘制坐标点的接口,就写了个脚本把他的数据爬了下来,写入一个json文件,只拿codename就够用了

温馨提示

为了方便使用我已经将抓好的json数据放到了仓库中 ./JSON/all.json,可以直接取用,当然你也可以执行脚本抓取最新的数据

数据来源

http://datav.aliyun.com/tools/atlas/

开源地址

https://gitee.com/yang230147961/get-city-list.git

环境

Python3.x

requests

安装使用

拉取代码

git clone https://gitee.com/yang230147961/get-city-list.git

cd ./get-city-list

安装依赖

pip install -r requirements.txt or pip3 install -r requirements.txt

执行脚本

python getCityList.py or python3 getCityList.py

实现逻辑

他这个接口逻辑是按层查询的,获取到第一层的 省份列表后,拿code去查这个省下面的市,然后拿每一个市的code再去查下面的区,以此类推,但是有些城市例如北京,只有2层,有的城市例如山东,有3层的,所以选择使用递归的方式去抓取数据

实现代码

import requests
mainCode = 100000
mainName = \'中华人民共和国\'
def getList(rootCode,rootName,lv):
    myData={
        \'code\':rootCode,
        \'name\':rootName,
    }
    api = \'https://geo.datav.aliyun.com/areas/bound/geojson?code={}_full\'.format(rootCode)
    data = requests.get(api)
    if data.json():
        arr = []
        index = 1
        for i in data.json().get(\'features\'):
            item = i.get(\'properties\')
            mycode = item.get(\'adcode\')
            myname = item.get(\'name\')
            print(\'{}>  {}\'.format(\'|\' + \'=========\' * lv, myname))
            childrenNum = item.get(\'childrenNum\')
            if not mycode == rootCode and mycode and myname and not childrenNum == 0:
                thisData = getList(mycode, myname,lv+1)
                arr = [*arr, thisData]
            else:
                arr = [*arr, {
                    \'code\': mycode,
                    \'name\': myname,
                }]
        if not len(arr) == 0:
            myData[\'list\'] = arr
        return myData
    else:
        return {}
def main():
    arr = getList(mainCode,mainName,1)
    with open(\'./省市区.json\',\'w\') as file:
        file.write(str(arr))
        file.close()
if __name__==\'__main__\':
    main()

分类:

技术点:

相关文章:

  • 2021-07-12
  • 2021-11-02
  • 2021-08-30
  • 2021-05-13
  • 2021-12-04
猜你喜欢
  • 2021-12-04
  • 2021-09-22
  • 2021-06-07
  • 2021-12-04
  • 2021-11-11
相关资源
相似解决方案