獲取全國省市區數據 (提供json數據下載)


獲取全國省市區數據

起因

最近在做項目時需要用戶選擇配送地點,需要一個省市區的選擇器,但是網上找了半天沒有找到合適的數據,要么就是數據太久遠,不全,要么就是要收費,還有些第三方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()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM