利用高德和百度获取经纬度和地址

两个小程序

#-*- coding: utf8 -*-
#!usr/bin/env python3
# encoding: utf-8
# Filename:amap_api.py

import xlrd
import requests
import time
import sys


amap_key = '00b7eb4446f0f4e47a268de7feee37a0'  
city_search = '全国'  # 限制搜索区域 默认需要填写"全国",且city_limit为"false"
city_limit = 'false'  # 'true'代表需要限制,'false'代表不限制
file_input = "amap_input.xlsx"  # 输入文件的文件名
time0 = time.strftime('%Y%m%d', time.localtime(time.time()))  # 当前日期
file_result = 'amap_result-{}.csv'.format(time0)  # 输出文件的文件名


def load_from_xlsx(file):
    data = xlrd.open_workbook(file)
    table0 = data.sheet_by_name('Sheet1')
    nrows = table0.nrows
    return table0, nrows


def amap_search(keyword,id):
    parameters = {'keywords': keyword, 'key': amap_key, 'city': city_search,
                  'citylimit': city_limit, 'extensions': 'all'}
    url = 'http://restapi.amap.com/v3/place/text'
    r = requests.get(url, parameters, timeout=50)
    s = requests.session()
    s.keep_alive = False
    r.raise_for_status()
    result = r.json()  # json部分
    try:
        result = result['pois']
        if not result:
            return str(keyword) +','+str(id)+ ',None,None,None,None\n'
        else:
            for i in result:
                name = i['name']
                type0 = i['type']
                address = i['address']
                location = i['location']
                adname = i['adname']
                return str(keyword) +','+str(id)+ ',{},{},{},{},{}\n'.format(name, type0, address, adname, location)
    except:
        return str(keyword)+','+str(id)+ ',{},{},{},{},{}\n'.format(None, None, None, None, None)


def save_to_csv(text):
    with open(file_result, 'a+') as f:
        print(text)
        f.write(text)


def main():
    print('<<<<<正在读取文件>>>>>当前文件夹下:{}'.format(file_input))
    data = load_from_xlsx(file=file_input)
    table, nrows = data[0], data[1]
    print('共有{}行数据\n************************'.format(nrows))
    for i in range(nrows):
        print('正在处理第{}行数据'.format(i + 1))
        id = table.row_values(i)[0]
        key = table.row_values(i)[1]
        result_amap = amap_search(key,id)
        save_to_csv(result_amap)
        print('=========================\n')
    print('程序运行完成,输出到当前文件夹下的{}文件'.format(file_result))


if __name__ == "__main__":
    main()
    
#-*- coding:utf-8 -*-
'''
利用百度地图api实现地址位置搜索
'''
import requests,json,re,time,xlrd
from openpyxl import Workbook

wb1 = Workbook()
ws1 = wb1.active

time1 = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
name1 = '百度地图结果'.decode('utf-8') + time1 + '.xlsx'
ws1.append(['区域','查询字段','名称','类型','电话','地址','市','区/县'])

file1 = '查询字段.xlsx'.decode('utf-8')
data1 = xlrd.open_workbook(file1)
table1 = data1.sheet_by_index(0)

nows = table1.nrows
for x in range(nows):
    items = table1.row_values(x)
    if x == 0 :
        continue
    else:
        try:
            print items[0],items[1]
            address = items[1].encode('utf-8')
            # region = items[0]
            region = '全国'
            url = 'http://api.map.baidu.com/place/v2/suggestion'
            output = 'json'
            ak = 'ie1pboEhSttv7biL1iYj6kUI'
            uri = url + '?' + 'query=' + address + '&region=' + region +'&city_limit=false'+ '&output=' + output + '&ak=' + ak
            response = requests.get(uri)
            temp = response.json() #对json数据进行解析
            # print response.text
            # print temp
            name = temp['result'][0]['name']
            city = temp['result'][0]['city']
            district = temp['result'][0]['district']
            print name, city, district
            uid = temp['result'][0]['uid']
            url1 = 'http://api.map.baidu.com/place/v2/detail?uid='+uid+'&output=json&scope=2&ak='+ak
            res = requests.get(url1)
            mp = res.json() #对json数据进行解析
            # print res.text
            #print mp
            dz = mp['result']['address']
            lx = mp['result']['detail_info']['lng']
            try:
                tele = mp['result']['telephone']
                print tele
            except:
                tele = ''
                print '查询失败'.decode('utf-8')
            print dz, lx

            ws1.append([items[0], items[1], name, lx, tele, dz,city, district])
            if x % 30 == 0:
                wb1.save(name1)

        except:
            print '查询失败'.decode('utf-8')
            ws1.append([items[0],items[1],'',''])

wb1.save(name1)
raw_input('success')