1 # Author:979
2 # blog addr:http://www.cnblogs.com/home979/
3 import json
4 from urllib.request import urlopen, quote
5 import requests,csv
6
7 def getlnglat(address):
8 url = \'http://api.map.baidu.com/geocoder/v2/\'
9 output = \'json\'
10 ak = \'百度地图开放平台申请或者加QQ944485360请求作者帮助\' #\'你申请的密钥***\'
11 add = quote(address) #由于本文城市变量为中文,为防止乱码,先用quote进行编码
12 uri = url + \'?\' + \'address=\' + add + \'&output=\' + output + \'&ak=\' + ak
13 req = urlopen(uri)
14 res = req.read().decode() #将其他编码的字符串解码成unicode
15 temp = json.loads(res) #对json数据进行解析
16 return temp
17
18 file = open(\'D:\\爬虫数据分析\调用百度地图api\point.json\',\'w\') #建立json数据文件
19 with open(\'D:\\爬虫数据分析\调用百度地图api\各区域房价.csv\', \'r\') as csvfile: #打开csv
20 reader = csv.reader(csvfile)
21 for line in reader: #读取csv里的数据
22 # #忽略第一行
23 # if reader.line_num == 1: #由于第一行为变量名称,故忽略掉
24 # # line是个list,取得所有需要的值
25 b = line[0].strip() #将第一列city读取出来并清除不需要字符
26 c = line[1].strip()#将第二列price读取出来并清除不需要字符
27 lng = getlnglat(b)[\'result\'][\'location\'][\'lng\'] #采用构造的函数来获取经度
28 lat = getlnglat(b)[\'result\'][\'location\'][\'lat\'] #获取纬度
29 str_temp = \'{"lat":\' + str(lat) + \',"lng":\' + str(lng) + \',"count":\' + str(c) +\'},\'
30 print(str_temp) #也可以通过打印出来,把数据copy到百度热力地图api的相应位置上
31 file.write(str_temp) #写入文档
32 file.close() #保存
33 #百度地图web api使用说明:http://lbsyun.baidu.com/index.php?title=webapi/direction-api-v2
34 \'\'\'
35 原作者:博观厚积
36 链接:https://www.jianshu.com/p/773ff5f08a2c
37 來源:简书
38 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
39 \'\'\'