Python下用Google Map查询地址的经纬度

环境:python3

坑:python2在开了goagent后,运行查询程序会报错,"非法proxy",原理不明;

要点:urllib.parse.quote编码含中文地址的url,python才能正确解码处理

代码实现如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib
from urllib.request import urlopen
import json

def getGeoForAddress(address):
	# address = "上海市中山北一路121号"
	addressUrl = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address
    #中文url需要转码才能识别
	addressUrlQuote = urllib.parse.quote(addressUrl, ':?=/')
	response = urlopen(addressUrlQuote).read().decode('utf-8')
	responseJson = json.loads(response)
    #type of response is string
	# print(type(response))
    #type of responseJson is dict
	# print(type(responseJson))
	lat = responseJson.get('results')[0]['geometry']['location']['lat']
	lng = responseJson.get('results')[0]['geometry']['location']['lng']
	print(address + '的经纬度是: %f, %f'  %(lat, lng))
	return [lat, lng]

if __name__ == '__main__':
    main()


你可能感兴趣的:(python,网络爬虫,Linux)