可以在浏览器输入,看一下格式。
http://api.map.baidu.com/geocoder?key=f247cdb592eb43ebac6ccd27f796e2d2&output=json&address=北京市
先把url转成urlcode,然后读取网页,读到网页再用json读取内容。
完整代码如下:
from urllib import parse query = { 'key' : 'f247cdb592eb43ebac6ccd27f796e2d2', 'address': '北京市', 'output':'json', } base = 'http://api.map.baidu.com/geocoder?' url = base+parse.urlencode(query) import urllib.request doc = urllib.request.urlopen(url) s = doc.read().decode('utf-8') #一定要解码!!!! import json jsonData = json.loads(s) lat=jsonData['result']['location']['lat'] lng =jsonData['result']['location']['lng'] print(lat,lng)
import requests address = '北京市' url= 'http://api.map.baidu.com/geocoder?output=json&key=f247cdb592eb43ebac6ccd27f796e2d2&address='+str(address) response = requests.get(url) answer = response.json() lon = float(answer['result']['location']['lng']) lat = float(answer['result']['location']['lat']) print(lon,lat)