用python下载地图图像

时间:2013-09-04 09:57:01

标签: python google-maps parsing urllib

我正在尝试使用 urllib 模块在 python 中下载地图图像。但它总是失败。

  • 我尝试将urllib.urlopen()与一些参数变体
  • 一起使用
  • urllib.urlretrieve()
  • 中尝试过

但是它不起作用。
而且,当我看到图像url的源代码时,我没有找到图像文件。这是图片:https://maps.googleapis.com/maps/api/staticmap?center=31.0456,121.3997&zoom=12&size=320x385&sensor=false

源代码:

#-------------------------- PARSE IP ADDRESS  -------------------------------
import re
import urllib


try:
    mysite = urllib.urlopen('http://ip-api.com/line')
except urllib.HTTPError, e:
    print "Cannot retrieve URL: HTTP Error Code", e.code
except urllib.URLError, e:
   print "Cannot retrieve URL: " + e.reason[1]

list_of_params = mysite.read()
print list_of_params
ip_arr = list_of_params.splitlines()

#--------------------- HERE IS FIND MAP IMAGE --------------------------------------
try:
    map_page = urllib.urlopen('http://ip-api.com')
except urllib.HTTPError, e:
    print "Cannot retrieve URL: HTTP Error Code", e.code
except urllib.URLError, e:
    print "Cannot retrieve URL: " + e.reason[1]

#f = open("data.html", "w")
#f.write(str(mysite.read()))
#f.close()

#looking for this in page
pattern = re.findall(re.compile("url\(\'(https://maps\.googleapis\.com/maps/api/staticmap\?center=.*)\'"), page_get_map.read())
map_img_url = pattern[0].replace('&', '&')

#-------------------    DOWNLOAD MAP IMAGE And SAVE IT  ------------------------
#file_name = map_img_url.rsplit('/',1)[1]

try:
    get_map_img = urllib.urlretrieve(map_img_url, "staticmap.png")
except urllib.HTTPError, e:
    print "Cannot retrieve URL: HTTP Error Code", e.code
except urllib.URLError, e:
    print "Cannot retrieve URL: " + e.reason[1]


i = open("pict.png", "w")
i.write(get_map_img.read())
i.close()

print "End of file"

2 个答案:

答案 0 :(得分:4)

import requests
f=open('static.png','wb')
f.write(requests.get('https://maps.googleapis.com/maps/api/staticmap?center=31.0456,121.3997&zoom=12&size=320x385&sensor=false').content)
f.close()

答案 1 :(得分:1)

为什么要解析地图网址?自己构建:

import json, urllib

query = '' # IP to get coordinates of, leave empty for current IP

geo = urllib.urlopen('http://ip-api.com/json/%s?fields=240' % query)
result = json.load(geo)
if result['zip']:
    zoom = 13
elif result['city']:
    zoom = 12
else:
    zoom = 6
map_img_url = "https://maps.googleapis.com/maps/api/staticmap?center=%s,%s&zoom=%i&size=320x385&sensor=false" % (result['lat'], result['lon'], zoom)
get_map_img = urllib.urlretrieve(map_img_url, "staticmap.png")