栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python爬取网络图片

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python爬取网络图片

通过Python爬取网络图片

1、引入import
import os
import socket
import urllib2
2、函数主体部分
# 定义下载到本地的地址
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)

代码分析: 本部分代码通过path+secPath融合对图片下载到的具体地址进行定义。如果该地址不存在,则创建。
主要函数:
os.path.join(a,b) :将括号中的地址通过 a/b 的形式结合成完整的地址
os.path.exists():判断括号中地址是否存在,返回true或者false:
os.path.makedirs():创建新的地址

2.2 定义下载图片名称以及网络地址
# 定义下载图片的名称
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地址下信息,读取并写入该信息。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/445129.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号