您的位置:首页 > 其它

利用百度地图API测量深圳产业办公及公寓的通勤时间

2020-05-08 04:19 1781 查看

利用百度地图API测量深圳产业办公及公寓的通勤时间,占坑待补充

import asyncio
import aiohttp
import time
import xlrd
import xlwt
import json

#打开产办和公寓的地址,并将数据存入字典
xl=xlrd.open_workbook(r'D:\xx\深圳产业办公及公寓数据.xlsx',formatting_info=False)
sheet1=xl.sheet_by_index(0)
nrows=sheet1.nrows
chanyes={}
boyus={}
tasks=[]
result_finall=[]
for i in range(1,nrows):
a=sheet1.cell(i,2).value
b=sheet1.cell(i,1).value
chanyes[sheet1.cell(i,0).value]=(str(sheet1.cell(i,2).value)+","+str(sheet1.cell(i,1).value))
sheet2=xl.sheet_by_index(2)
nrows2=sheet2.nrows
for i in range(50,nrows2):
boyus[sheet2.cell(i,0).value]=(str(sheet2.cell(i,3).value)+","+str(sheet2.cell(i,2).value))
print(len(boyus),boyus)
print(len(chanyes),chanyes)
print('我完成提取了',time.time())

y=0

#构造获取距离时间函数并返回r.text()
async def getjuli(qidian,zhongdian,boyu,chanye):
url = "http://api.map.baidu.com/directionlite/v1/transit"
ak = "GMDxyc6PASRARvsgw8BzbAnfTH6Euah9"
#finurl = url+"origin="+qidian+"&destination="+zhongdian+"&ak="+ak
canshu={'origin':qidian,'destination':zhongdian,'ak':ak}
async with sem:
global y
async with aiohttp.ClientSession() as session:
async with session.get(url=url,params=canshu) as r:
a= await r.text(encoding='windows-1251')
try:
c= json.loads(a)
dura = round(c['result']['routes'][0]['duration'] / 60)
print('起点:{},终点:{},两点间通行时间为{}分钟'.format(chanye,boyu,dura))
result_finall.append([boyu,chanye,dura])
return result_finall
except Exception as e:
print('起点:{},终点:{},错误是{},'.format(boyu,chanye,e))
result_finall.append([boyu, chanye, e])
finally:
y = y + 1
print(f'第{y}次爬取')

#构造主函数及协程池
def async_main():
loop = asyncio.get_event_loop()
for boyu,boyudizhi in boyus.items():
for chanye, chanyedizhi in chanyes.items():
[tasks.append(asyncio.ensure_future(getjuli(boyudizhi,chanyedizhi,boyu,chanye)))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()

if __name__ == '__main__':
start = time.time()
print(start)
sem = asyncio.Semaphore(500)
async_main()
print(f'cost time: {time.time() - start}s')
wb = xlwt.Workbook()
sheetnew = wb.add_sheet('产业办公及公寓的距离', cell_overwrite_ok=True)
i=0
for result in result_finall:
sheetnew.write(i, 0, result[0])
sheetnew.write(i, 1, result[1])
sheetnew.write(i, 2, result[2])
print('{}存储成功{}'.format(result,i))
i=i+1
wb.save(r'D:\xxx.xls')
print(f'一切完成cost time: {time.time() - start}s')
cyincy 原创文章 2获赞 0访问量 156 关注 私信
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: