当前位置 博文首页 > 你要控制住你自己的博客:python请求百度地图API 获取地理坐标

    你要控制住你自己的博客:python请求百度地图API 获取地理坐标

    作者:[db:作者] 时间:2021-07-29 18:40

    python请求百度地图API 获取地理坐标

    因为最近需要获取一批住址信息的地理坐标就简单做了一个爬虫
    获取地址信息的地理坐标。


    百度api步骤

    第一步:选择开发文档的 Web 服务API.在这里插入图片描述第二步:注册开发者 获取密钥
    在这里插入图片描述第三步:选择正/逆地理编码 查看开发文档就能看到接口
    在这里插入图片描述

    注意

    接口使用需要你自己申请的ak 密钥可以直接拼接在接口的 &ak= 后面,地址拼接在 address= 后面

    分析完了直接上代码

    用python的requests 请求接口

    #数据库请求模块
    import pymysql
    
    host ='127.0.0.1'
    user = 'root'
    pwd = '123456'
    db = 'gb18030'
    port  = 3306
    
    
    
    def list_fetchall(sql):
        conn = pymysql.connect(host=host, user=user, passwd=pwd, port=port, db=db)
        cursor = conn.cursor()
        cursor.execute(sql)
        rows = cursor.fetchall()
        row = [item[0] for item in rows]
        cursor.close()
        conn.close()
        return row
    
    def conn_exec(sql):
        conn = pymysql.connect(host=host, user=user, passwd=pwd, port=port, db=db)
        cursor = conn.cursor()
        num = cursor.execute(sql)
        cursor.connection.commit()
        cursor.close()
        conn.close()
        return num
    
    
    sql = 'select `住宅地址` from `人员住址信息`'
    add_data = list_fetchall(sql)
    
    #因为我的地理数据是从数据库来的所以上边是数据库请求
    for ad in add_data:
        url = "http://api.map.baidu.com/geocoding/v3/?address=%s&output=json&ak=R1nD1Nx8p7KPTAH2FmECfEH8TEPURGvO&callback=showLocation" %(ad)
    
        headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36'}
        res = requests.get(url,headers=headers)
        res.data = res.content.decode()
       
       #因为有的地址信息不太标准,所以最好加一个异常处理
        try:
            res.data = res.data.split('(')[1].replace(')','')
            res.data = json.loads(res.data)
            res.data = str(res.data['result']['location']['lng'])+','+str(res.data['result']['location']['lat'])
            #这里我是存到数据库 你也可以存到txt 或者 excel 表里面
            up_sql = "update `人员住址信息` set `地理坐标`='%s' where 住宅地址='%s'" %(res.data,ad)
            print(up_sql)
            conn_exec(up_sql)
        except Exception as f:
            print(f)
    
    

    注意

    值得注意的是这个api接口返回的是这样的一个字符串,没有办法直接用json.loads()转换为python数据
    需要将头部的showLocation&&showLocation去掉 当然这里我把()也去掉了 直接转换为python 字典。
    这样就可以用字典访问方式进行数据读取了。 “lng”:113.25828787722539,“lat”:23.155081435873187 就是
    获取的经纬度信息。

    showLocation&&showLocation({"status":0,"result":{"location":{"lng":113.25828787722539,"lat":23.155081435873187},"precise":0,"confidence":75,"comprehension":0,"level":"购物"}})
    

    尾注

    因为我也是第一次用百度的这个地理编码接口,很多地方讲的可能有不对的地方,还希望博友多多包涵,并加以指正。

    cs