0

我正在尝试使用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"
4

2 回答 2

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()
于 2013-09-04T13:40:37.277 回答
1

为什么要解析地图 URL?自己构建它:

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")
于 2013-09-04T11:24:01.480 回答