Skip to content

Instantly share code, notes, and snippets.

@upbit
Created Nov 27, 2015
Embed
What would you like to do?
百度geo反查例子
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
sys.dont_write_bytecode = True
import urllib
import hashlib
import json
import requests
from pyv8 import PyV8
from bs4 import BeautifulSoup
# http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
BAIDU_GEOCODING_URL = "http://api.map.baidu.com/geocoder/v2/"
BAIDU_APP_AK = ""
BAIDU_APP_SK = ""
# Copyright: Liao Xuefeng (https://github.com/michaelliao/sinaweibopy/blob/master/weibo.py)
class JsonDict(dict):
"""general json object that allows attributes to be bound to and also behaves like a dict"""
def __getattr__(self, attr):
try:
return self[attr]
except KeyError:
raise AttributeError(r"'JsonDict' object has no attribute '%s'" % attr)
def __setattr__(self, attr, value):
self[attr] = value
def parse_json(s):
"""parse str into JsonDict"""
def _obj_hook(pairs):
"""convert json object to python object"""
o = JsonDict()
for k, v in pairs.iteritems():
o[str(k)] = v
return o
return json.loads(s, object_hook=_obj_hook)
def geocoder_v2(address, city=None):
if city:
queryStr = '/geocoder/v2/?address=%s&city=%s&output=json&ak=%s' % (address, city, BAIDU_APP_AK)
else:
queryStr = '/geocoder/v2/?address=%s&output=json&ak=%s' % (address, BAIDU_APP_AK)
encodedStr = urllib.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
rawStr = encodedStr + BAIDU_APP_SK
sn = hashlib.md5(urllib.quote_plus(rawStr)).hexdigest()
if city:
r = requests.get("http://api.map.baidu.com/geocoder/v2/?address=%s&city=%s&output=json&ak=%s&sn=%s" % (address, city, BAIDU_APP_AK, sn))
else:
r = requests.get("http://api.map.baidu.com/geocoder/v2/?address=%s&output=json&ak=%s&sn=%s" % (address, BAIDU_APP_AK, sn))
if not r.status_code in [200]:
raise Exception("[HTTP %s] %s" % (r.status_code, r.text))
return parse_json(r.text)
def geocoder_v2_reverse(location):
lat = location['lat']
lng = location['lng']
queryStr = '/geocoder/v2/?location=%s,%s&output=json&ak=%s&pois=1' % (lat, lng, BAIDU_APP_AK)
encodedStr = urllib.quote(queryStr, safe="/:=&?#+!$,;'@()*[]")
rawStr = encodedStr + BAIDU_APP_SK
sn = hashlib.md5(urllib.quote_plus(rawStr)).hexdigest()
r = requests.get("http://api.map.baidu.com/geocoder/v2/?location=%s,%s&output=json&ak=%s&pois=1&sn=%s" % (lat, lng, BAIDU_APP_AK, sn))
if not r.status_code in [200]:
raise Exception("[HTTP %s] %s" % (r.status_code, r.text))
return parse_json(r.text)
def search_geo_by_name(name, city=None):
loc_result = geocoder_v2(name, city).result
result = geocoder_v2_reverse(loc_result.location).result
addr = result.addressComponent
true_poi = try_get_true_poi(name, result.pois)
return {
'precise': loc_result.precise,
'confidence': loc_result.confidence,
'address': result.formatted_address,
'province': addr['province'],
'city': addr['city'],
'district': addr['district'],
'street': addr['street'],
'poi': true_poi,
}
def try_get_true_poi(name, pois):
u_name = unicode(name)
for poi in pois:
if u_name == poi.name:
return {
'name': poi['name'],
'addr': poi['addr'],
'type': poi['poiType'],
'location': poi['point'],
}
return None
def main():
for k,v in search_geo_by_name("腾讯大厦").items():
print k, v
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment