1、引入import通过Python爬取网络图片
import os import socket import urllib22、函数主体部分
# 定义下载到本地的地址
secPath = str(i)
path = r"D:workimg_downloadonaci_img"
# 创建本地文件夹:
path = os.path.join(path,secPath)
Ex = os.path.exists(path)
if not Ex:
os.makedirs(path)
# 定义下载图片的名称
z = str(i)
x = str(j/2**i)
y = str(j%2**i)
name = z + "-" + x + "-" + y + ".jpg"
# filename:下载图片路径+名称
filename = os.path.join(path,name)
f = open(filename, 'wb')
# 定义下载图片的网络地址
url ="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile"+"/"+z+"/"+x+"/"+y
# req = urllib.urlopen('https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/1/0/1')
try:
req = urllib2.urlopen(url,timeout=20)
except urllib2.URLError as e:
if isinstance(e.reason,socket.timeout):
print ("超时",j)
buf = req.read()
f.write(buf)
代码刨析
2.1 定义下载到本地地址部分代码
# 定义下载到本地的地址
secPath = str(i)
path = r"D:workimg_downloadonaci_img"
# 创建本地文件夹:
path = os.path.join(path,secPath)
Ex = os.path.exists(path)
if not Ex:
os.makedirs(path)
2.2 定义下载图片名称以及网络地址代码分析: 本部分代码通过path+secPath融合对图片下载到的具体地址进行定义。如果该地址不存在,则创建。
主要函数:
os.path.join(a,b) :将括号中的地址通过 a/b 的形式结合成完整的地址
os.path.exists():判断括号中地址是否存在,返回true或者false:
os.path.makedirs():创建新的地址
# 定义下载图片的名称 z = str(i) x = str(j/2**i) y = str(j%2**i) name = z + "-" + x + "-" + y + ".jpg" # filename:下载图片路径+名称 filename = os.path.join(path,name) f = open(filename, 'wb') # 定义下载图片的网络地址 url ="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile"+"/"+z+"/"+x+"/"+y
2.3 下载、写入下载图片的名称:可完全自命名
下载图片的网络地址:该地址需要非常详细,即当你访问该地址网页时,可具体到该图片
%%% 该地址可访问,仅用于学习用途,若侵犯请联系删除 %%%
try:
req = urllib2.urlopen(url,timeout=20)
except urllib2.URLError as e:
if isinstance(e.reason,socket.timeout):
print ("超时",j)
buf = req.read()
f.write(buf)
通过req = urllib2.urlopen(url),访问url地址下信息,读取并写入该信息。



