最近有同事让我帮忙把一些网页本地静态化,中间遇到一些问题,比如css的图片下载到本地,并替换路径
无法用webzip,所以就自己写个简单工具实现了。代码如下:
String proxyHost = 'proxy ip'
String proxyPort = '8080'
System.setProperty("proxyHost", proxyHost)
System.setProperty("proxyPort", proxyPort)
// 匹配css文件中的image路径的正则
def pat = /.+url\(([^\)]+)\).+/
def getImg = {url, cssPath ->
String name = url.split(/\//)[-1]
def targetFile = new File('../image/' + name)
if(!targetFile.exists()){
// 如果是相对路径,就根据css的绝对路径获取image的绝对路径
if(url.startsWith('../')){
url = cssPath + '/' + url
}
// 下载到文件
def os = new FileOutputStream(targetFile)
os << new URL(url).openStream()
println 'done for ' + name
}else{
println 'skip for ' + name
}
}
def downImg = {f, host, cssPath ->
def ll = []
f.eachLine{
def mat = it =~ pat
if(mat){
String url = mat[0][1]
try {
getImg(host + url, cssPath)
String name = url.split(/\//)[-1]
it = it.replace(url, '../image/' + name)
ll << it
}catch (ex) {
ex.printStackTrace()
}
}else{
ll << it
}
}
// css文件内容重新替换,因为图片路径变化
f.withPrintWriter{w ->
for(line in ll){
w.println line
}
}
}
downImg(new File('my.css'), 'http://test.myhost.com', '/app/my.css')
TIPS:如果需要设置代理,需要前4行