1、根据URL请求获取页面HTML代码
- /// <summary>
- /// 获取网页的HTML码
- /// </summary>
- /// <param name="url">链接地址</param>
- /// <param name="encoding">编码类型</param>
- /// <returns></returns>
- public static string GetHtmlStr(string url, string encoding)
- {
- string htmlStr = "";
- if (!String.IsNullOrEmpty(url))
- {
- WebRequest request = WebRequest.Create(url); //实例化WebRequest对象
- WebResponse response = request.GetResponse(); //创建WebResponse对象
- Stream datastream = response.GetResponseStream(); //创建流对象
- Encoding ec = Encoding.Default;
- if (encoding == "UTF8")
- {
- ec = Encoding.UTF8;
- }
- else if (encoding == "Default")
- {
- ec = Encoding.Default;
- }
- StreamReader reader = new StreamReader(datastream, ec);
- htmlStr = reader.ReadToEnd(); //读取数据
- reader.Close();
- datastream.Close();
- response.Close();
- }
- return htmlStr;
- }
2、下载网站图片
- /// <summary>
- /// 下载网站图片
- /// </summary>
- /// <param name="picUrl"></param>
- /// <returns></returns>
- public string SaveAsWebImg(string picUrl)
- {
- string result = "";
- string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"/File/"; //目录
- try
- {
- if (!String.IsNullOrEmpty(picUrl))
- {
- Random rd = new Random();
- DateTime nowTime = DateTime.Now;
- string fileName = nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + ".jpeg";
- WebClient webClient = new WebClient();
- webClient.DownloadFile(picUrl, path + fileName);
- result = fileName;
- }
- }
- catch { }
- return result;
- }
版权声明:本文为博主原创文章,未经博主允许不得转载。