C#獲取網頁的HTML碼、下載網站圖片
一、根據URL請求獲取頁面HTML代碼html
- public static string GetHtmlStr(string url, string encoding)
- {
- string htmlStr = "";
- if (!String.IsNullOrEmpty(url))
- {
- WebRequest request = WebRequest.Create(url);
- WebResponse response = request.GetResponse();
- 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;
- }
二、下載網站圖片web
- 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;
- }
歡迎關注本站公眾號,獲取更多信息