码迷,mamicode.com
首页 > 编程语言 > 详细

python3 高德常用方法归类

时间:2020-03-21 21:21:15      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:read   json   inf   replace   orm   计时   math   csv   length   

高德秘钥的设置以及检测

 1 import requests
 2 import time
 3 import csv
 4 from math import ceil
 5 
 6 
 7 class KEY:
 8     def __init__(self):
 9         self.keys = list(csv.reader(open(u高德秘钥.csv, r)))
10         self.keys_length = len(self.keys)
11         self.i = 0
12 
13     def get_key(self):
14         return self.keys[self.i][1]
15 
16     def next_key(self):
17         self.i += 1
18         if self.i == self.keys_length:
19             self.i = 0
20             now_time = time.localtime(time.time())
21             time.sleep((23-now_time[3])*3600+(60-now_time[4])*60)
22         return self.get_key()
23 
24     def check_out(self):
25         lon = 104.12159
26         lat = 30.65447
27         while self.i < self.keys_length:
28             print(self.i)
29             base_url = https://restapi.amap.com/v3/assistant/coordinate/convert
30             _params_ = {locations: {},{}.format(lon, lat),
31                         coordsys: gps, output: json, key: self.keys[self.i][1]}
32 
33             infocode = int(requests.get(base_url, _params_).json()[infocode])
34             if infocode == 10001:
35                 print(self.keys[self.i])
36 
37             self.i += 1
38             time.sleep(1)

 

代码测试

1 k = KEY()
2 k.check_out()

 

常用方法总结

  1 class Method:
  2     def __init__(self):
  3         self.keys = KEY()
  4         self.k = self.keys.get_key()
  5 
  6     # 访问网址
  7     def get_response(self, base_url_, params_):
  8         """
  9         :param base_url_:  网址
 10         :param params_: 访问网址的参数字典
 11         :return: 访问网址的响应内容
 12         """
 13         while True:
 14             try:
 15                 response_ = requests.get(base_url_, params_)
 16                 response_ = response_.json()
 17                 infocode = int(response_[infocode])
 18                 if infocode != 10000:
 19                     print(infocode, self.k)
 20                     self.k = self.keys.next_key()
 21                     params_[key] = self.k
 22                 else:
 23                     break
 24             except requests.exceptions.ConnectionError:
 25                 print(wait a moment)
 26                 for i in range(60, 0, -1):
 27                     print("倒计时{}秒".format(i), flush=True, end="\b"*5)
 28                     time.sleep(1)
 29             except Exception as e:
 30                 print(e)
 31         return response_
 32 
 33     # gps坐标转化高德坐标
 34     def exchange(self, coordinate):
 35         """
 36         :param coordinate: 坐标 经度,纬度|经度,纬度……
 37         :return: 高德坐标
 38         """
 39         base_url = https://restapi.amap.com/v3/assistant/coordinate/convert
 40         _params_ = {locations: coordinate, coordsys: gps, output: json, key: self.k}
 41 
 42         return self.get_response(base_url, _params_)[locations].replace(;, |)
 43 
 44     # 获取行政区信息
 45     def get_region(self, *args, coordinate=‘‘,  batch=False):
 46         """
 47         :param coordinate: 坐标字符串
 48         :param args: 坐标 经度,纬度|经度,纬度……
 49         :param batch: 批量查询
 50         :return: 省,市,区(县),详细地址
 51         """
 52         if coordinate == ‘‘:
 53             temp = []
 54             for i in range(0, len(args), 2):
 55                 temp.append({},{}.format(args[i], args[i+1]))
 56             str_coordinate = |.join(temp)
 57         else:
 58             str_coordinate = coordinate
 59 
 60         base_url = https://restapi.amap.com/v3/geocode/regeo
 61         _params_ = {location: self.exchange(str_coordinate), extensions: all,
 62                     output: json, key: self.k, batch: str(batch).lower()}
 63 
 64         response = self.get_response(base_url, _params_)
 65 
 66         if not batch:
 67             province = response[regeocode][addressComponent][province]
 68             city = response[regeocode][addressComponent][city]
 69             district = response[regeocode][addressComponent][district]
 70             address = response[regeocode][formatted_address]
 71             pois = [[r[type].split(;)[0], float(r[distance])] for r in response[regeocode][pois][:3]]
 72 
 73             return province, city, district, address, pois
 74         else:
 75             regeocodes = response[regeocodes]
 76             result = []
 77             for r in regeocodes:
 78                 result.append(
 79                     (
 80                         r[addressComponent][province],
 81                         r[addressComponent][city],
 82                         r[addressComponent][district],
 83                         r[formatted_address],
 84                         [[i[type].split(;)[0], float(i[distance])] for i in r[pois][:3]]
 85                     )
 86                 )
 87             return result
 88 
 89     # 获取POI信息(多边形搜索--矩形搜索)
 90     def get_poi(self, lon, lat, lon_gap, lat_gap, poi_type, output_poiname=False):
 91         """
 92         :param lon: 矩形中心经度
 93         :param lat: 矩形中心纬度
 94         :param lon_gap: 矩形经度间隔
 95         :param lat_gap: 矩形纬度间隔
 96         :param poi_type: 查询POI类型
 97         :param output_poiname: 输出POI name
 98         :return: 相应poi数量
 99         """
100         base_url = https://restapi.amap.com/v3/place/polygon
101         params = {polygon: self.exchange({},{}|{},{}.
102                                            format(lon-lon_gap/2, lat+lat_gap/2, lon+lon_gap/2, lat-lat_gap/2)),
103                   types: poi_type, output: json, key: self.k, page: 1, offset: 20}
104 
105         response = self.get_response(base_url, params)
106         n = int(response[count])
107 
108         if output_poiname:
109             print(Crawling POI {} name.format(poi_type))
110             name = [{}({}).format(e[name], e[typecode]) for e in response[pois]]
111             while params[page] < ceil(n/20):
112                 params[page] += 1
113                 name += [{}({}).format(e[name], e[typecode]) for e in self.get_response(base_url, params)[pois]]
114 
115             return n, name
116         else:
117             return n
118 
119     def get_distance(self, o_lon, o_lat, d_lon, d_lat):
120         base_url = https://restapi.amap.com/v3/direction/driving
121         parameters = {
122             key: self.k, strategy: 2, nosteps: 1, extensions: base,
123             origin: self.exchange({},{}.format(o_lon, o_lat)),
124             destination: self.exchange({},{}.format(d_lon, d_lat))
125         }
126 
127         response = self.get_response(base_url, parameters)
128 
129         return float(response[route][paths][0][distance])

 

代码测试

1 lon_ = 104.12159
2 lat_ = 30.65447
3 m = Method()
4 print(m.get_region(lon_, lat_, lon_, lat_, batch=True))

 

lon_ = 104.12159
    lat_ = 30.65447
    m = Method()
    print(m.get_region(lon_, lat_, lon_, lat_, batch=True))

python3 高德常用方法归类

标签:read   json   inf   replace   orm   计时   math   csv   length   

原文地址:https://www.cnblogs.com/jpapplication/p/12541874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!