C#获取网页的HTML码、下载网站图片

1、根据URL请求获取页面HTML代码

  1. /// <summary>  
  2. /// 获取网页的HTML码  
  3. /// </summary>  
  4. /// <param name="url">链接地址</param>  
  5. /// <param name="encoding">编码类型</param>  
  6. /// <returns></returns>  
  7. public static string GetHtmlStr(string url, string encoding)  
  8. {  
  9.     string htmlStr = "";  
  10.     if (!String.IsNullOrEmpty(url))  
  11.     {  
  12.         WebRequest request = WebRequest.Create(url);            //实例化WebRequest对象  
  13.         WebResponse response = request.GetResponse();           //创建WebResponse对象  
  14.         Stream datastream = response.GetResponseStream();       //创建流对象  
  15.         Encoding ec = Encoding.Default;  
  16.         if (encoding == "UTF8")  
  17.         {  
  18.             ec = Encoding.UTF8;  
  19.         }  
  20.         else if (encoding == "Default")  
  21.         {  
  22.             ec = Encoding.Default;  
  23.         }  
  24.         StreamReader reader = new StreamReader(datastream, ec);  
  25.         htmlStr = reader.ReadToEnd();                           //读取数据  
  26.         reader.Close();  
  27.         datastream.Close();  
  28.         response.Close();  
  29.     }  
  30.     return htmlStr;  
  31. }  
 

 

2、下载网站图片

  1. /// <summary>  
  2. /// 下载网站图片  
  3. /// </summary>  
  4. /// <param name="picUrl"></param>  
  5. /// <returns></returns>  
  6. public string SaveAsWebImg(string picUrl)  
  7. {  
  8.     string result = "";  
  9.     string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/File/";  //目录  
  10.     try  
  11.     {  
  12.         if (!String.IsNullOrEmpty(picUrl))  
  13.         {  
  14.             Random rd = new Random();  
  15.             DateTime nowTime = DateTime.Now;  
  16.             string fileName = nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + ".jpeg";  
  17.             WebClient webClient = new WebClient();  
  18.             webClient.DownloadFile(picUrl, path + fileName);  
  19.             result = fileName;  
  20.         }  
  21.     }  
  22.     catch { }  
  23.     return result;  
  24. }  
 
版权声明:本文为博主原创文章,未经博主允许不得转载。
posted @ 2015-11-16 12:11  qq260250932  阅读(284)  评论(0编辑  收藏  举报