C#制造多線程處置強化版收集爬蟲。本站提示廣大學習愛好者:(C#制造多線程處置強化版收集爬蟲)文章只能為提供參考,不一定能成為您想要的結果。以下是C#制造多線程處置強化版收集爬蟲正文
前次做了一個幫公司妹子做了爬蟲,不是很精細,此次公司項目裡要用到,因而有做了一番修正,功效添加了網址圖片收集,下載,線程處置界面網址圖片下載等。
說說思緒:輔弼獲得初始網址的一切內容 在初始網址收集圖片 去初始網址收集鏈接 把收集到的鏈接放入隊列 持續收集圖片,然後持續收集鏈接,無窮輪回
照樣上圖片年夜家看一下,
處置網頁內容抓取跟網頁網址爬取都做了改良,上面照樣年夜家來看看代碼,有缺乏的地方,還請的地方!
網頁內容抓取HtmlCodeRequest,
網頁網址爬取GetHttpLinks,用正則去挑選html中的Links
圖片抓取GetHtmlImageUrlList,用正則去挑選html中的Img
都寫進了一個封裝類外面 HttpHelper
/// <summary> /// 獲得HTML中一切圖片的 URL。 /// </summary> /// <param name="sHtmlText">HTML代碼</param> /// <returns>圖片的URL列表</returns> public static string HtmlCodeRequest(string Url) { if (string.IsNullOrEmpty(Url)) { return ""; } try { //創立一個要求 HttpWebRequest httprequst = (HttpWebRequest)WebRequest.Create(Url); //不樹立耐久性鏈接 httprequst.KeepAlive = true; //設置要求的辦法 httprequst.Method = "GET"; //設置標頭值 httprequst.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; httprequst.Accept = "*/*"; httprequst.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5"); httprequst.ServicePoint.Expect100Continue = false; httprequst.Timeout = 5000; httprequst.AllowAutoRedirect = true;//能否許可302 ServicePointManager.DefaultConnectionLimit = 30; //獲得呼應 HttpWebResponse webRes = (HttpWebResponse)httprequst.GetResponse(); //獲得呼應的文本流 string content = string.Empty; using (System.IO.Stream stream = webRes.GetResponseStream()) { using (System.IO.StreamReader reader = new StreamReader(stream, System.Text.Encoding.GetEncoding("utf-8"))) { content = reader.ReadToEnd(); } } //撤消要求 httprequst.Abort(); //前往數據內容 return content; } catch (Exception) { return ""; } } /// <summary> /// 提取頁面鏈接 /// </summary> /// <param name="html"></param> /// <returns></returns> public static List<string> GetHtmlImageUrlList(string url) { string html = HttpHelper.HtmlCodeRequest(url); if (string.IsNullOrEmpty(html)) { return new List<string>(); } // 界說正則表達式用來婚配 img 標簽 Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase); // 搜刮婚配的字符串 MatchCollection matches = regImg.Matches(html); List<string> sUrlList = new List<string>(); // 獲得婚配項列表 foreach (Match match in matches) sUrlList.Add(match.Groups["imgUrl"].Value); return sUrlList; } /// <summary> /// 提取頁面鏈接 /// </summary> /// <param name="html"></param> /// <returns></returns> public static List<string> GetHttpLinks(string url) { //獲得網址內容 string html = HttpHelper.HtmlCodeRequest(url); if (string.IsNullOrEmpty(html)) { return new List<string>(); } //婚配http鏈接 const string pattern2 = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"; Regex r2 = new Regex(pattern2, RegexOptions.IgnoreCase); //取得婚配成果 MatchCollection m2 = r2.Matches(html); List<string> links = new List<string>(); foreach (Match url2 in m2) { if (StringHelper.CheckUrlIsLegal(url2.ToString()) || !StringHelper.IsPureUrl(url2.ToString()) || links.Contains(url2.ToString())) continue; links.Add(url2.ToString()); } //婚配href外面的鏈接 const string pattern = @"(?i)<a\s[^>]*?href=(['""]?)(?!javascript|__doPostBack)(?<url>[^'""\s*#<>]+)[^>]*>"; ; Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //取得婚配成果 MatchCollection m = r.Matches(html); foreach (Match url1 in m) { string href1 = url1.Groups["url"].Value; if (!href1.Contains("http")) { href1 = Global.WebUrl + href1; } if (!StringHelper.IsPureUrl(href1) || links.Contains(href1)) continue; links.Add(href1); } return links; }
這邊下載圖片有個義務條數限制,限制是200條。假如跨越的話線程期待5秒,這裡下載圖片是異步驟用的拜托
public string DownLoadimg(string url) { if (!string.IsNullOrEmpty(url)) { try { if (!url.Contains("http")) { url = Global.WebUrl + url; } HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 2000; request.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705"; //能否許可302 request.AllowAutoRedirect = true; WebResponse response = request.GetResponse(); Stream reader = response.GetResponseStream(); //文件名 string aFirstName = Guid.NewGuid().ToString(); //擴大名 string aLastName = url.Substring(url.LastIndexOf(".") + 1, (url.Length - url.LastIndexOf(".") - 1)); FileStream writer = new FileStream(Global.FloderUrl + aFirstName + "." + aLastName, FileMode.OpenOrCreate, FileAccess.Write); byte[] buff = new byte[512]; //現實讀取的字節數 int c = 0; while ((c = reader.Read(buff, 0, buff.Length)) > 0) { writer.Write(buff, 0, c); } writer.Close(); writer.Dispose(); reader.Close(); reader.Dispose(); response.Close(); return (aFirstName + "." + aLastName); } catch (Exception) { return "毛病:地址" + url; } } return "毛病:地址為空"; }
話不多說,更多的須要年夜家本身去改良咯!迎接讀者來與樓主停止交換。