代码如下:
from urllib import request
import os
import urllib
def get_abs_paths(directory, totalPathFiles=[]):
'''
此函数旨在获取directory目录下,所有文件的绝对路径,
并放在totalPathFiles里。
directory,目标目录。
'''
FFs = os.listdir(directory)
# print(FFs)
for f in FFs:
totalPathFile = os.path.join(directory, f)
if os.path.isfile(totalPathFile):
# print(totalPathFile)
totalPathFiles.append(totalPathFile)
else:
get_abs_paths(totalPathFile)
return totalPathFiles
def get_html(url, user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0', num_retries=10):
"""支持user-agent并且可以尝试多次爬取数据的爬虫"""
#print('Downloading:', url)
# user-agent设置
headers = {'User-agent': user_agent}
req = request.Request(url, headers=headers)
# print(req)
try:
response = request.urlopen(req)
html = response.read()
# 出错的处理
except urllib.error.URLError as e:
##print('Download error:', e.reason)
html = None
# 多次出错的处理
if num_retries > 0:
if hasattr(e, 'code') and 500 <= e.code < 600:
# retry 5XX HTTP errors
# 服务器出错,递归反复尝试
get_html(url, user_agent, num_retries-1)
return html
def mkdirs(path):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
# 创建目录操作函数
os.makedirs(path)
print(path+' 创建成功')
return True
else:
# 如果目录存在则不创建,并提示目录已存在
print(path+' 目录已存在')
return False
def write_json_b3dm(pathFile, fileContent):
'''
此函数用于保存json和b3dm文件。
pathFile,文件的绝对路径,类似这样:D:/3dtiles/bim-youeryuan/tileset.json。
fileContent,文件内容,二进制形式。
'''
mkdirs("/".join(pathFile.split("/")[:-1]))
with open(pathFile, "wb") as f:
f.write(fileContent)
print(pathFile + " 已下载。")
def handleDownloadFailure(url):
'''
此函数用于,处理获取到的html=None的情况。
处理操作:
在保存根目录下,创建downloadFailure.txt文件,记录下载失败的情况。
'''
global saveRootFolder
# 该文件存在,则添加内容。
if os.path.exists(saveRootFolder + "downloadFailure.txt"):
with open(saveRootFolder + "downloadFailure.txt", "a") as f:
f.write(url + " downloadFailure!\n")
# 不存在,则创建、添加内容。
else:
with open(saveRootFolder + "downloadFailure.txt", "w") as f:
f.write(url + " downloadFailure!\n")
def downloadFile(url, saveRootFolder):
'''
下载一个文件。
url, 该文件的接口,比如:http://data.marsgis.cn/3dtiles/bim-youeryuan/tileset.json
saveRootFolder,该文件要保存的根路径。
该文件保存的真实路径,要由url + saveRootFolder共同决定,
比如:D:/3dtiles/bim-youeryuan/tileset.json。
'''
# 保存文件的绝对路径。
pathFile = saveRootFolder + "/".join(url.split("/")[3:])
# 文件内容。字节串,或None。
html = get_html(url)
if html == None:
print("error: html == None!!!")
handleDownloadFailure(url)
return
# 写文件。
write_json_b3dm(pathFile, html)
def main(url, saveRootFolder):
'''
主函数。
'''
# 下载入口json文件。
downloadFile(url, saveRootFolder)
if __name__ =="__main__":
# 文件接口类似: http://cesium.marsgis.cn/lib/cesium/cesium.js
# 文件保存路径: D:/lib/cesium/cesium.js
directory = r"D:\Cesium2"
totalPathFiles = get_abs_paths(directory)
# print("totalPathFiles:", totalPathFiles)
# print(len(totalPathFiles))
saveRootFolder = "D:/"
i = 0
for f in totalPathFiles:
f = f.replace("D:\\Cesium2", "http://cesium.marsgis.cn/lib/cesium")
f = f.replace("\\",'/')
i += 1
print(i)
print(f)
main(f, saveRootFolder)
print("done")