copy网页的工具脚本分享

最近有同事让我帮忙把一些网页本地静态化,中间遇到一些问题,比如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行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值