c# 自动解析页面中图片链接并下载到本地
发表时间:2023-07-19 来源:明辉站整理相关软件相关文章人气:
[摘要]自动解析网页中图片链接并下载到本地做CMS的时候,需要采集别人的文章但是里面的图片好多都是动态的,所以需要下载到本地比较好,下面是基本代码。using System;using System.Tex...
自动解析网页中图片链接并下载到本地
做CMS的时候,需要采集别人的文章但是里面的图片好多都是动态的,所以需要下载到本地比较好,下面是基本代码。
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace zhang.Common
{
public class HanlerFiles
{
private string[] GetImgTag(string htmlStr)
{
Regex regObj = new Regex("", RegexOptions.Compiled RegexOptions.IgnoreCase);
string[] strAry = new string[regObj.Matches(htmlStr).Count];
int i = 0;
foreach (Match matchItem in regObj.Matches(htmlStr))
{
strAry[i] = GetImgUrl(matchItem.Value);
i++;
}
return strAry;
}
private string GetImgUrl(string imgTagStr)
{
string str = "";
Regex regObj = new Regex("http://.+.(?:jpg gif bmp png)", RegexOptions.Compiled RegexOptions.IgnoreCase);
foreach (Match matchItem in regObj.Matches(imgTagStr))
{
str = matchItem.Value;
}
return str;
}
/**////
/// 根椐Html内空自动识别图像文件,并下载到服务器指定目录
///
///
///
///
public int SaveUrlPics(ref string strHTML, string path)
{
string[] imgurlAry = GetImgTag(strHTML);
try
{
for (int i = 0; i < imgurlAry.Length; i++)
{
//WebRequest req = WebRequest.Create(imgurlAry[i]);
string preStr = System.DateTime.Now.ToString() + "_";
preStr = preStr.Replace("-", "");
preStr = preStr.Replace(":", "");
preStr = preStr.Replace(" ", "");
WebClient wc = new WebClient();
wc.DownloadFile(imgurlAry[i], HttpContext.Current.Server.MapPath(path) + "/" + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
strHTML = strHTML.Replace(imgurlAry[i], path + preStr + imgurlAry[i].Substring(imgurlAry[i].LastIndexOf("/") + 1));
}
}
catch (Exception ex)
{
//return ex.Message;
}
return imgurlAry.Length;
}
}
}
学习教程快速掌握从入门到精通的电脑知识