使用Python中的Google Maps geocoder和urllib2 [英] Using Google Maps geocoder from Python with urllib2

查看:84
本文介绍了使用Python中的Google Maps geocoder和urllib2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Python和JSON上使用Google Maps地理编码器,但一直告诉我有一个错误的请求:

  add =白金汉宫,伦敦,SW1A 1AA
geocode_url =https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&region=uk %add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(f.read())
pprint.pprint(nest)

这会导致 urllib2.HTTPError失败:HTTP错误400:错误请求



但如果我简单地复制并粘贴

  https:// maps.googleapis.com/maps/api/geocode/json?address=Buckingham%20Palace,%20London,%20SW1A%201AA&sensor=false&region=uk 

到浏览器栏中,它工作正常。



我的请求出了什么问题?

解决方案

您需要一些网址引用编码,这是可行的:

  import urllib2 
import pprint
import json
add =白金汉宫,伦敦SW1A 1AA
add = urllib2.quote(add)
geocode_url =http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&region=uk%add
print geocode_url
req = urllib2.urlopen (geocode_url)
jsonResponse = json.loads(req.read())
pprint.pprint(jsonResponse)

add = urllib2.quote(add)是重要的一点。如果你有非拉丁字符,建议谷歌API需要UTF-8编码。


I'm trying to use the Google Maps geocoder with Python and JSON, but keep being told I have a bad request:

add = "Buckingham Palace, London, SW1A 1AA"
geocode_url = "https://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&region=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(f.read())
pprint.pprint(nest) 

This fails with urllib2.HTTPError: HTTP Error 400: Bad Request.

But if I simply copy and paste

https://maps.googleapis.com/maps/api/geocode/json?address=Buckingham%20Palace,%20London,%20SW1A%201AA&sensor=false&region=uk

into a browser bar, it works fine.

What is wrong with my request?

解决方案

You need some URL quoting encoding, this works:

import urllib2
import pprint
import json
add = "Buckingham Palace, London, SW1A 1AA"
add = urllib2.quote(add)
geocode_url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false&region=uk" % add
print geocode_url
req = urllib2.urlopen(geocode_url)
jsonResponse = json.loads(req.read())
pprint.pprint(jsonResponse) 

The line add = urllib2.quote(add) is the important point. If you have non latin characters be advised that the google API needs UTF-8 encoding.

这篇关于使用Python中的Google Maps geocoder和urllib2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆