Python+百度地图开放平台API获取指定范围内商家信息实例

Python+百度地图开放平台API获取指定范围内商家信息实例,第1张

本文主要分享自己对于百度地图开放平台API使用的经验分享,算是对学习过的相关优质内容做一个集成整和,本文的实例以代码为主,以搜寻XXX市内的所有万达广场周边X千米内的所有超市信息(经纬度,地址,电话等信息)并保存成XLS文件;

1.百度地图开放平台API的申请(个人开发者认证)过程

这篇文章写的非常详细,我就不赘述了,大家可以直接参考

§1 打开百度地图的大门——注册百度地图开发者账户与创建应用_菡萏_花开的博客-CSDN博客

这里也附上官网链接:

百度地图开放平台 | 百度地图API SDK | 地图开发

2.控制台内应用的创建

控制台内应用主要有两种创建方式

第1种是AK码IP白名单方式,第2种是AK码+SN码

我们分别用两种方式各创建一个应用;

3.Python代码,这里使用的Anaconda自带的Spyder编辑器,不需要额外安装包

import requests
import json
import time
import xlwt
import urllib.request, urllib.parse, urllib.error
import hashlib
import xlrd
import webbrowser as wb
"""
    查询关键字:
"""
FileKey = 'preclass'


def requestBaiduApi0(keyWords, baiduAk, fileKey,region):
    today = time.strftime("%Y-%m-%d")
    pageNum = 0
    count = -1
    logfile = open("./" + fileKey + "-" + today + ".log", 'a+', encoding='utf-8')
    book=xlwt.Workbook(encoding='utf-8',style_compression=0)
    sheet=book.add_sheet('MAP',cell_overwrite_ok=True)

    # print('-------------')
    # print(index)
    while True:
        try:
            URL = "http://api.map.baidu.com/place/v2/search?query=" + keyWords + \
                "®ion=" + region + \
                "&output=json" +  \
                "&ak=" + baiduAk + \
                "&scope=2" + \
                "&page_size=20" + \
                "&page_num=" + str(pageNum)
            # print(pageNum)
            print(URL)
            resp = requests.get(URL)
            res = json.loads(resp.text)
            # print(resp.text.strip())
            if len(res['results']) == 0:
                logfile.writelines(time.strftime("%Y%m%d%H%M%S") + " stop " + " " + str(pageNum) + '\n')
                break
            else:
                for r in res['results']:
                    # print(r)
                    city_area = r['city']+r['area']
                    shop_name = r['name']
                    shop_lat = str(r['location']['lat'])
                    shop_lng = str(r['location']['lng'])
                    shop_ad = r['address']
                    shop_url =r['detail_info']['detail_url']
                    shop_tag = r['detail_info']['tag']
                    try:
                        shop_telephone = r['telephone']+'\t'
                    except Exception:
                        shop_telephone = "暂无"       
                    count = count + 1
                    print(city_area,shop_name, shop_ad,shop_tag,shop_telephone,shop_lat,shop_lng,shop_url)
                    print("\n")   
                    """
                    sheet.write(0,0,"地区")
                    sheet.write(0,1,"名称")
                    sheet.write(0,2,"详细地址")
                    sheet.write(0,3,"行业分类")
                    sheet.write(0,4,"电话号码")
                    sheet.write(0,5,"纬度")
                    sheet.write(0,6,"经度")
                    sheet.write(0,7,"地图链接")
                    """                    
                    sheet.write(count,0,city_area)
                    sheet.write(count,1,shop_name)
                    sheet.write(count,2,shop_ad)
                    sheet.write(count,3,shop_tag)
                    sheet.write(count,4,shop_telephone)
                    sheet.write(count,5,shop_lat)
                    sheet.write(count,6,shop_lng)
                    sheet.write(count,7,shop_url)
                    sheet.col(0).width=256*15
                    sheet.col(1).width=256*30
                    sheet.col(2).width=256*40
                    sheet.col(3).width=256*15
                    sheet.col(4).width=256*20
                    sheet.col(5).width=256*12
                    sheet.col(6).width=256*12
                    sheet.col(7).width=256*40
            pageNum += 1
            time.sleep(1)
            book.save(region+'内'+keyWords+'类商家检索信息.xls')
        except:
            print("except")
            logfile.writelines(time.strftime("%Y%m%d%H%M%S") + " except " + " " + str(pageNum) + '\n')
            break  
        
def get_url(name,MyAK1,MySK1):
    queryStr = '/geocoding/v3/?address={}&output=json&ak={}'.format(name,MyAK1)
    encodedStr = urllib.parse.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
    rawStr = encodedStr + MySK1
    sn = (hashlib.md5(urllib.parse.quote_plus(rawStr).encode("utf8")).hexdigest())
    url = urllib.parse.quote("http://api.map.baidu.com" + queryStr + "&sn=" + sn, safe="/:=&?#+!$,;'@()*[]")
    print('URL:', url)
    return url

def get_json(url):
    req = urllib.request.urlopen(url)
    res = req.read().decode()
    try:
        json_data = json.loads(res)
    except:
        json_data = None
    if not json_data or 'status' not in json_data or json_data['status'] != 0:
        print('json数据获取失败')
    else:
        print(json.dumps(json_data, indent=4, ensure_ascii=False))
    return json_data

def get_lnglat(json_data):
    lat = json_data["result"]["location"]["lat"]
    lng = json_data["result"]["location"]["lng"]
    print('纬度', lat, '经度', lng)
    return [lat,lng]
    
def requestBaiduApi(keyWords, baiduAk, fileKey,lat2,lng2,cont,Radius):
    today = time.strftime("%Y-%m-%d")
    pageNum = 0
    count = 0
    logfile = open("./" + fileKey + "-" + today + ".log", 'a+', encoding='utf-8')
    book=xlwt.Workbook(encoding='utf-8',style_compression=0)
    sheet=book.add_sheet('MAP',cell_overwrite_ok=True)
    while True:
        try:
            URL = "https://api.map.baidu.com/place/v2/search?query=" + keyWords + \
                "&location="+lat2 + "," + lng2 + \
                "&radius="+radius+ \
                "&output=json" +  \
                "&ak=" + baiduAk + \
                "&scope=2" + \
                "&page_size=20" + \
                "&page_num=" + str(pageNum)
            print(URL)
            resp = requests.get(URL)
            res = json.loads(resp.text)
            if len(res['results']) == 0:
                logfile.writelines(time.strftime("%Y%m%d%H%M%S") + " stop " + " " + str(pageNum) + '\n')
                break
            else:
                for r in res['results']:
                    count = count+1
                    city_area = r['city']+r['area']
                    shop_name = r['name']
                    shop_lat = str(r['location']['lat'])
                    shop_lng = str(r['location']['lng'])
                    shop_ad = r['address']
                    shop_tag = r['detail_info']['tag']
                    shop_distance = r['detail_info']['distance']
                    shop_url =r['detail_info']['detail_url']
                    try:
                        shop_telephone = r['telephone']+'\t'
                    except Exception:
                        shop_telephone = "暂无"  
                    try:
                        shop_overallrating = r['detail_info']['overall_rating']
                    except Exception:
                        shop_overallrating = "暂无"
                    try:
                        comment_num = r['detail_info']['comment_num']
                    except Exception:
                        comment_num = "暂无"                   
                    print(city_area,shop_name, shop_ad,shop_tag,shop_distance,shop_telephone,shop_lat,shop_lng,shop_overallrating,comment_num,shop_url)
                    print("\n")
                    sheet.write(0,0,"地区")
                    sheet.write(0,1,"名称")
                    sheet.write(0,2,"详细地址")
                    sheet.write(0,3,"行业分类")
                    sheet.write(0,4,"距离(米)")
                    sheet.write(0,5,"电话号码")
                    sheet.write(0,6,"纬度")
                    sheet.write(0,7,"经度")
                    sheet.write(0,8,"商家总体评分")
                    sheet.write(0,9,"互联网平台近期点评次数")
                    sheet.write(0,10,"地图链接")
                    sheet.write(count,0,city_area)
                    sheet.write(count,1,shop_name)
                    sheet.write(count,2,shop_ad)
                    sheet.write(count,3,shop_tag)
                    sheet.write(count,4,shop_distance)
                    sheet.write(count,5,shop_telephone)
                    sheet.write(count,6,shop_lat)
                    sheet.write(count,7,shop_lng)
                    sheet.write(count,8,shop_overallrating)
                    sheet.write(count,9,comment_num)
                    sheet.write(count,10,shop_url)
                    sheet.col(0).width=256*15
                    sheet.col(1).width=256*30
                    sheet.col(2).width=256*40
                    sheet.col(3).width=256*15
                    sheet.col(4).width=256*9
                    sheet.col(5).width=256*20
                    sheet.col(6).width=256*12
                    sheet.col(7).width=256*12
                    sheet.col(8).width=256*12
                    sheet.col(9).width=256*23
                    sheet.col(10).width=256*40
            pageNum += 1
            time.sleep(1)
            book.save(cont+'_周边'+Radius+'米_'+keyWords+'类商家检索.xls')
        except:
            print("except")
            logfile.writelines(time.strftime("%Y%m%d%H%M%S") + " except " + " " + str(pageNum) + '\n')
            break

def requestBaiduApi2(keyWords, baiduAk, fileKey,lat2,lng2,cont,Radius):
    URL = "https://api.map.baidu.com/place/search?query=" + keyWords + \
                "&location="+lat2 + "," + lng2 + \
                "&radius="+Radius+ \
                "&output=html&src=webapp.bocfintech.mapshopsearchtest"
    print(URL)
    return URL
    

if __name__ == '__main__':
    #---------------------------------------------
    #api参数:
    AK1 = '此处填STEP2创建的第一个应用的AK码'
    SN1 = '此处填STEP2创建的第一个应用的SN校验码'
    AK2 = '此处填STEP2创建的第二个应用的AK码'
    #目标中心点群信息:
    RegionS = "上海市"#xxx市或xx市xx区
    KeyWordS = "万达广场"
    #目标中心点群周边信息:
    RadiusM = "5000"#检索半径,单位米
    Sort = "超市"
    #----------------------------------------------  
    requestBaiduApi0(keyWords=KeyWordS, baiduAk=AK2, fileKey=FileKey,region=RegionS)
    time.sleep(0.5)
    worksheet = xlrd.open_workbook(RegionS+'内'+KeyWordS+'类商家检索信息.xls')
    sheet_name= "MAP"
    sheet = worksheet.sheet_by_name(sheet_name)
    rows = sheet.nrows # 获取行数
    cols = sheet.ncols # 获取列数,尽管没用到
    all_content = []
    cols = sheet.col_values(1) # 获取第x列内容, 数据格式为此数据的原有格式(原:字符串,读取:字符串;  原:浮点数, 读取:浮点数)
    print(cols)
    for col in range(len(cols)):
      content= RegionS+cols[col] #检索中心点(名称/地址)
      radius = RadiusM #检索半径,单位:米
      pic = "0" #是否调起百度地图Web,值为1则起调
      url=get_url(content,MyAK1=AK1,MySK1=SN1)
      json_data=get_json(url)
      lnglat=get_lnglat(json_data)
      requestBaiduApi(keyWords= Sort, baiduAk=AK2, fileKey=FileKey,lat2=str(lnglat[0]),lng2=str(lnglat[1]),cont=content,Radius=radius)
      if pic == "1":
         wb.open(requestBaiduApi2(keyWords= Sort, baiduAk=AK2, fileKey=FileKey,lat2=str(lnglat[0]),lng2=str(lnglat[1]),cont=content,Radius=radius), new=1, autoraise=True)

代码实现效果如下

第一个XLS内容为上海市内万达广场的信息

余下其他XLS的内容为第一个XLS内具体万达广场周边5000米所有超市的详细信息,下图为例

补充:本文及代码均参考学习过CSDN及各平台其他博主,只是根据自己的需要进行整合,代码中的几部分函数亦可拆开单独使用,推荐学习百度地图API开发文档了解更多相关知识。

地点检索 | 百度地图API SDK

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/918876.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-16
下一篇 2022-05-16

发表评论

登录后才能评论

评论列表(0条)

保存