Python 位置名称通过高德API获取行政区划信息ByMySQL

本文介绍了一个Python脚本,用于从高德地图API获取医院信息并自动更新数据库。通过批量处理和性能优化,减少了API调用次数,同时实现了数据库的高效同步。

先上代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# coding=utf-8
import pymysql
import requests


def get_infor(hospit_name, region="全国"):  # return list
    response = requests.get(
        'https://restapi.amap.com/v5/place/text?parameters&key=【高德Key】&keywords=%s&region=%s&types=【Pois code】' % (
            hospit_name[1], region))

    data_info = response.json()
    # print(data_info)
    data_results = data_info['pois']
    json_key_name = ['name', 'address', 'pname', 'cityname', 'adname']
    i = 0
    for i in range(len(data_results)-1):
        for key_name in json_key_name:
            if not get_not_emtpy(data_results[i-1], key_name):
                i += 1
            else:
                break

    if i == len(data_results) - 1:
        print('Don‘t find optimum result ,so select default number zero by  list data!!!')
        i = 0
    try:
        # todo
        data_one_result = data_results[0]
    except BaseException:
        print('empty data! Next...')
        return None

    print('Count result size:', len(data_results))
    print('select result number:', i)
    print('Select result white Excel file:', data_results[i])

    return data_one_result


def get_not_emtpy(result_json, key_name):
    if result_json[key_name] is None:
        return False
    else:
        return True


def read_target_data():
    db = pymysql.connect(host="192.168.0.150", user="root", password="cd520888", database="open_cell")

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()

    # SQL 查询语句
    sql = "SELECT * FROM amap"
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results_sql_data = cursor.fetchall()
        results_sql_arrays_data = []
        for result_sql_data in results_sql_data:
            results_sql_array_data = []
            for i in result_sql_data:
                results_sql_array_data.append(i)

            results_sql_arrays_data.append(results_sql_array_data)

        # print(results_sql_arrays_data)
        return results_sql_arrays_data
    except:
        print("Error: unable to fetch data")

    # 关闭数据库连接
    db.close()

def batch_updata_data(result):
    batch_updata_sql = "UPDATE amap SET name = (%s), address = (%s), pname = (%s), cityname = (%s), adname = (%s) WHERE id = (%s)"
    results_update_sql_data = []
    for i in result:
        i.append(i[0])
        del i[0]
        del i[0]
        results_update_sql_data.append(i)

    db = pymysql.connect(host="***", user="***", password="***", database="***")

    # 使用cursor()方法获取操作游标
    cursor = db.cursor()
    cursor.executemany(batch_updata_sql, results_update_sql_data)
    db.commit()
    db.close()
    print('done!')

if __name__ == '__main__':
    sql_data = read_target_data()
    n = -1  # 行数计数变量
    cell_num = 0

    # 重复分段,优化性能减少API消耗
    a = []
    x = []
    for i in range(0, len(sql_data)):
        if i + 1 < len(sql_data):
            if sql_data[i][1] == sql_data[i + 1][1]:
                x.append(sql_data[i])
            else:
                x.append(sql_data[i])
                a.append(x)
                x = []
        else:
            x.append(sql_data[len(sql_data) - 1])
            a.append(x)

    count = 0
    for element in a:
        count = count + 1

    for count_this in range(count):
        result_data = get_infor(a[count_this][0])
        for result_data_for in range(len(a[count_this])):
            n += 1
            if result_data is not None:
                sql_data[n][2] = result_data['name']
                sql_data[n][3] = result_data['address']
                sql_data[n][4] = result_data['pname']
                sql_data[n][5] = result_data['cityname']
                sql_data[n][6] = result_data['adname']
                print('done,', len(sql_data) - 1 - n, 'left')
            else:
                print('failed', len(sql_data) - 1 - n, 'left')

    batch_updata_data(sql_data)

'''python'''

目前这个版本经过了一定程度的上的性能优化

使用说明

1.填入高德地图开放平台Key
2.根据所需要转换的地理位置行业属性,按照高德提供的typs 表格数据,进行填写
3.填写数据库连接信息

数据库表结构
在这里插入图片描述
数据说明

请将要进行API调用的地理名称,导入到数据库old_name字段中。

### 批量调用高德地图API获取多个坐标的省市信息 在实际应用场景中,通常需要对多个经纬度坐标进行批量处理以获取对应的省、市等行政区划信息高德地图 API 支持通过设置 `batch=true` 参数一次性请求最多 10 个坐标点的逆地理编码信息[^3]。 #### 请求方式与参数说明 高德地图的逆地理编码接口为: ``` https://restapi.amap.com/v3/geocode/regeo ``` 支持以下关键参数: - `key`: 高德开发者密钥(必填) - `location`: 经纬度坐标,格式为 `经度,纬度`,多个坐标之间使用 `|` 分隔 - `batch`: 是否启用批量查询,值设为 `true`,最多支持 10 个坐标点 #### 示例代码 以下是一个完整的 Python 脚本示例,演示如何批量调用高德地图 API 并提取每个坐标的省份和城市信息: ```python import requests def batch_get_province_and_city(locations, key): url = "https://restapi.amap.com/v3/geocode/regeo" params = { "key": key, "location": locations, "batch": "true" } response = requests.get(url, params=params) data = response.json() if data["status"] == "1" and data["info"] == "OK": results = [] for item in data["regeocodes"]: location = item["formatted_address"] province = item["addressComponent"]["province"] city = item["addressComponent"].get("city", "N/A") results.append({ "location": location, "province": province, "city": city }) return results else: print("API Error:", data.get("info")) return [] # 示例调用 key = "YOUR_AMAP_API_KEY" # 替换为你的高德 API Key locations = "116.310792,39.997422|113.264358,23.129162|121.473702,31.230416" # 北京、广州、上海坐标 results = batch_get_province_and_city(locations, key) for res in results: print(f"地址: {res['location']}, 省份: {res['province']}, 城市: {res['city']}") ``` 该脚本将输出类似如下内容: ``` 地址: 北京市朝阳区北辰西路8号, 省份: 北京市, 城市: 北京市 地址: 广州市天河区体育西路189号, 省份: 广东省, 城市: 广州市 地址: 上海市黄浦区南京东路100号, 省份: 上海市, 城市: 上海市 ``` #### 注意事项 - 每次请求应确保 `key` 合法有效,并遵守高德平台的频率限制。 - 若需处理超过 10 个坐标点,可分批请求并控制时间间隔,避免触发限流机制。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

图幺陆零

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值