你的位置:首页 > ASP.net教程

[ASP.net教程]提取网站图片


protected void sub_Click(object sender, EventArgs e)
{
int i = 0;
string url = this.url.Text;
Directory.CreateDirectory("D:/aspnetjia/"+url);
string result = GetWebRequest(url);
//this.content.InnerText = result;
MatchCollection results = Regex.Matches(result, @"<img\s[^>]*src=([""']*)(?<src>[^'""]*)\1[^>]*>", RegexOptions.IgnoreCase);
string[] d = new string[results.Count];
foreach (Match m in results)
{
d[i] = m.Groups["src"].Value;
i++;
}
for (int j = 0; j < d.Length; j++)
{
string jieguo = "";
int jj = j + 1;
string jie = d[j].ToString();
//if (jie.Contains(url))
//{
// jie.Replace(url,"");
//}
if (jie.Contains("www.") || jie.Contains("http"))
{
jieguo = "<a href='"+jie+"'><img src='"+jie+"'></a>";
}
else
{
jieguo = "<a href='" + url + "/" + jie + "'><img src='" + url + "/" + jie + "'></a>";
}
Random rand = new Random();//定义一个随机数,为了防止你要上传得图片重名
string[] strSpil = jie.Split('.');//将此地址用.号进行分割(img/1.jpg)
string strEnd = strSpil[strSpil.Length - 1].ToLower();//得到后面的("jpg", "gif", "bmp", "png","jpeg","JPG","GIF","BMP","PNG","JPEG")

string strName = DateTime.Now.ToString("yyyymmmddhhss") + rand.Next(100, 9999).ToString();//得到不同得名字
string strPointEnd = strName+"."+strEnd;

System.Net.WebClient myWebClient = new System.Net.WebClient();
if (jie.Contains("http"))
{
myWebClient.DownloadFile(jie, "D:/aspnetjia/" +url+"/"+strPointEnd);
}
else
{
myWebClient.DownloadFile(url +"/"+jie, "D:/aspnetjia/"+url +"/"+strPointEnd);
}
//Response.Write("正在下载第"+j+"张...");
}
Response.Write("请查看你D盘下aspnetjia文件夹");
}
private string GetWebRequest(string url)
{
Uri uri = new Uri(url);
WebRequest myReq = WebRequest.Create(uri);
WebResponse result = myReq.GetResponse();
Stream receviceStream = result.GetResponseStream();
StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8"));
string strHTML = readerOfStream.ReadToEnd();
readerOfStream.Close();
receviceStream.Close();
result.Close();
return strHTML;
}

转载自:http://www.aspnetjia.com