Python获取全国区划代码名称及中心经纬度
代码
import requests
from bs4 import BeautifulSoup as BS
ak = "****"
def get_location_by_region_name(region_name):
url = f"https://api.map.baidu.com/geocoding/v3/?address={region_name}&output=json&ak={ak}"
content = requests.get(url).json()
try:
location = content["result"]["location"]
lon, lat = location["lng"], location["lat"]
return (lon, lat)
except:
print(f"{region_name}获取位置出错!")
return None
def get_all_region_codes():
url = "http://www.mca.gov.cn/article/sj/xzqh/2020/20201201.html"
content = requests.get(url).text
bs = BS(content, "lxml")
table = bs.find("table")
region_list = list()
for tr in table.find_all("tr"):
tds = tr.find_all("td")
if len(tds)<3 or tds[1].text == "":
continue
code, name = tds[1].text.strip(), tds[2].text.strip()
if code == "行政区划代码":
continue
elif code.endswith("0000"):
level = "省"
elif code.endswith("00"):
level = "市"
else:
level = "区"
region_list.append((level,code,name))
return region_list
if __name__ == "__main__":
file_path = "region.csv"
with open(file_path, 'w') as f:
f.write("区划级别,区划编码,区划名称,经度,纬度\n")
for (level,code,name) in get_all_region_codes():
location = get_location_by_region_name(name)
if not location:
lon, lat = "",""
else:
lon, lat = location
line = f"{level},{code},{name},{lon},{lat}"
print(f"{level},{code},{name},{lon},{lat}")
f.write(line+"\n")
print(f"全国区划经纬度信息写入{file_path}完成!")
数据
|