当前位置: 移动技术网 > IT编程>开发语言>Asp > 用asp自动解析网页中的图片地址

用asp自动解析网页中的图片地址

2017年12月12日  | 移动技术网IT编程  | 我要评论
一,取得原页中的图片的地址。
<%
function picstr(str)
 set objregexp = new regexp '设置配置对象
 objregexp.ignorecase = true '忽略大小写
 objregexp.global = true '设置为全文搜索
 objregexp.pattern = "<img.+?>" '为了确保能准确地取出图片地址所以分为两层配置:首先找到里面的<img>标签,然后再取出里面的图片地址后面的getimgs函数就是实现后一个功能的。
 strs=trim(str)
 set matches =objregexp.execute(strs) '开始执行配置
 for each match in matches
 picstr = picstr &getimgs( match.value ) '执行第二轮的匹配
 next
 '所有的图片在里面都是这样的src="http://图片的地址",所以可以这样来取得确切的图片地址
end function

function getimgs(str)
 getimgs=""
 set objregexp1 = new regexp
 objregexp1.ignorecase = true
 objregexp1.global = true
 objregexp1.pattern = "http://.+?""" '取出里面的地址
 set mm=objregexp1.execute(str)
 for each match1 in mm
 getimgs=getimgs&"||"&left(match1.value,len(match1.value)-1) '把里面的地址串起来备用
 next
end function
%>

二,下载图片并保存在服务器上。
<%
function gethttppage(url)
  on error resume next
  dim http
  set http=server.createobject("msxml2.xmlhttp") '使用xmlhttp的方法来获得图片的内容
  http.open "get",url,false
  http.send()
  if http.readystate<>4 then
  exit function
  end if
  gethttppage=http.responsebody
  set http=nothing
  if err.number<>0 then err.clear
end function
'取得了图片的内容要保存,给人一种感觉是用fso来作就可以了,但实际上不行,这样保存程序就会出错,因为fso不支持流式的文件,所以我们要调用另一个对象:ado.strem。具体的过程如下:
function saveimage(from,tofile)
  dim geturl,objstream,imgs
  geturl=trim(from)
  imgs=gethttppage(geturl)'取得图片的具休内容的过程
  set objstream = server.createobject("adodb.stream")'建立adodb.stream对象,必须要ado 2.5以上版本
  objstream.type =1'以二进制模式打开
  objstream.open
  objstream.write imgs'将字符串内容写入缓冲
  objstream.savetofile server.mappath(tofile),2'-将缓冲的内容写入文件
  objstream.close()'关闭对象
  set objstream=nothing
end function

'所以只要用一个循环来把刚才取得的地址中的图片全部保存下来,具体过程如下:
arrimg=split(picstr(str),"||") '分割字串,取得里面地址列表
allimg=""
newimg=""
for i=1 to ubound(arrimg)
if arrimg(i)<>"" and instr(allimg,arrimg(i))<1 then '看这个图片是否已经下载过
fname=baseurl&cstr(i&mid(arrimg(i),instrrev(arrimg(i),".")))
saveimage(arrimg(i),fname)‘保存地址的函数,过程见上面
allimg=allimg&"||"&arrimg(i) '把保存下来的图片的地址串回起来,以确定要替换的地址
newimg=newimg&"||"&fname '把本地的地址串回起来
end if
next
'第三步就是替换原来的地址了。具体的过程就是下面了:
arrnew=split(newimg,"||") '取得原来的图片地址列表
arrall=split(allimg,"||") '取得已经保存下来的图片的地址列表
for i=1 to ubound(arrnew) '执行循环替换原来的地址
  strs=replace(strs,arrall(i),arrnew(i))
next
%>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网