获取小区名字
import numpy as np
import requests
import pymysql
import time, math
print("connecting mysql......\n")
db = pymysql.connect("localhost", "root", "123456", "community", charset='utf8')
print("connect successfully,start creating table community_zh in database community\n")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS community_zh")
c_sql = """CREATE TABLE community_zh(
province char(10),
city char(10),
area char(10),
community char(30),
address char(50),
lat float(9,6),
lng float(9,6),
uid char(25),
detail int(1)
)"""
cursor.execute(c_sql)
cursor.execute("ALTER TABLE community_zh CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;")
print("table community_zh has been created\n")
unit = 60
lat_partion = [round(x,6) for x in list(np.linspace(21.874881,22.418767, unit))]
lng_partion = [round(y,6) for y in list(np.linspace(113.112379,113.641301, unit))]
def get_community():
for i in range(53, 59):
for j in range(0, 59):
not_max_page = True
page_num = 0
while not_max_page:
url = "http://api.map.baidu.com/place/v2/search?query=小区&page_size=20&page_num=" + str(page_num) + "\
&bounds=" + str(lat_partion[i]) + "," + str(lng_partion[j])+"," + str(lat_partion[i+1]) + "," + str(lng_partion[j+1]) + \
"&output=json&ak="
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
response = requests.get(url, headers = header)
time.sleep(1)
answer = response.json()
total = int(answer["total"])
max_page = math.ceil(total / 20)
if answer['status'] == 0:
print("\n# Rectangle (%d,%d) Page %s" % (i, j, page_num))
print("# Amount: %s" % len(answer['results']))
print("# Total: %s" % total)
page_num += 1
if page_num > max_page:
break
for k in range(len(answer['results'])):
province = answer['results'][k]['province']
if province == "澳门特别行政区":
break
city = answer['results'][k]['city']
area = answer['results'][k]['area']
community = answer['results'][k]['name']
address = answer['results'][k]['address']
lat = answer['results'][k]['location']['lat']
lng = answer['results'][k]['location']['lng']
uid = answer['results'][k]['uid']
detail = answer['results'][k]['detail']
insert_data = ("INSERT INTO community_zh(province, city, area, community, address, lat, lng, uid, detail)""VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s)")
community_data = ([province, city, area, community, address, lat, lng, uid, detail])
print(community_data)
cursor.execute(insert_data, community_data)
db.commit()
else:
print("* The rectangle (%d,%d) contains no community"%(i, j))
break
if __name__=='__main__':
get_community()
获取小区边界
import requests
import pymysql
import time, math
def meter2Degree(x, y):
url = "http://api.map.baidu.com/geoconv/v1/?coords="+ x + "," + y + "&from=6&to=5&output=json&ak="
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
response = requests.get(url, headers = header)
answer = response.json()
result = answer["result"]
lng = result[0]["x"]
lat = result[0]["y"]
return lng, lat
def coordinateToPoints(coordinates):
points = ""
if coordinates and coordinates.index("-") >= 0:
coordinates = coordinates.split("-")
temp_coordinates = coordinates[1]
if temp_coordinates and temp_coordinates.index(",") >= 0:
temp_coordinates = temp_coordinates.replace(";", "").split(",")
temp_points = []
for i in range(0, len(temp_coordinates), 2):
x = temp_coordinates[i]
y = temp_coordinates[i + 1]
point = {}
point["x"] = x
point["y"] = y
temp_points.append(point)
for point in temp_points:
x = point["x"]
y = point["y"]
lng, lat = meter2Degree(x, y)
points += str(lng) + "," + str(lat) + ";"
return points
def getBorder(uid):
url = "http://map.baidu.com/?pcevaname=pc4.1&qt=ext&ext_ver=new&l=12&uid=" + uid
header = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
response = requests.get(url, headers = header)
answer = response.json()
content = answer["content"]
points = ""
if "geo" in content and content["geo"] != None and content["geo"] != "":
geo = content["geo"]
points = coordinateToPoints(geo)
return points
if __name__ == "__main__":
print("connecting mysql......\n")
db = pymysql.connect("localhost", "root", "123456", "community", charset='utf8')
print("connect successfully,start creating table community_zh in database community\n")
cursor = db.cursor()
cursor.execute("select community,uid from community_zh")
rows = cursor.fetchall()
start_flag = False
with open("./community_border.txt", "a") as wf:
for row in rows:
name = row[0]
uid = row[1]
if name == "香溪兴苑(小区)":
start_flag = True
if start_flag:
points = getBorder(uid)
time.sleep(1)
content = name + "\t" + points + "\n"
print(content)
wf.write(content)