C#——作一個簡單代理IP池

1、原因。

  抓取數據時,有一些網站 設置了一些反爬蟲設置,進而將本身本地 IP 地址拉入系統黑名單。從而達到禁止本地 IP 訪問數據的請求。

 

 

2、思路。

  根據其餘 代理 IP 網站,進行一個免費的代理 IP 進行蒐集,而後進行統一 驗證 管理

以下圖:html

 

 

3、抓取包含代理 IP 的網站頁面。

 

  抓取來網站代碼以後,利用 HtmlAgilityPack 進行 html 的解析。並將代理 IP 驗證,存放隊列等操做。git

 

4、直接看效果圖。

  運行效果。

 

 

  

 

 

 

瀏覽器 請求 :http://127.0.0.1:12306/ 效果。github

 

 

 

就這樣,一個簡單的  屬於本身的 代理 IP 池,就作好了 。。。瀏覽器

 

放上 關於 HttpListener 監聽的代碼網站

  

public static void Lisener() { Console.Title = url; HttpListener listerner = new HttpListener(); { listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份驗證 Anonymous匿名訪問
 listerner.Prefixes.Add(url); listerner.Start(); new Thread(new ThreadStart(delegate { while (true) { HttpListenerContext httpListenerContext = listerner.GetContext(); new Thread(new ThreadStart(delegate { HttpListenerContext ctx = httpListenerContext; try { using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { ctx.Response.StatusCode = 200; string ipp = ctx.Request.QueryString["ipp"]; if (null != ipp && Regex.IsMatch(ipp, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\:\d{1,5}$")) { Console.WriteLine("{0}> 刪除代理{1}", DateTime.Now.ToString("s"), ipp); QueueOperation(new ProxyViewModel() { Id = ipp }, IQueueType.Del); writer.WriteLine("true"); } else { int count = 0; while (true) { if (count > 10) { writer.WriteLine("false"); break; } // 出隊已個代理IP對象
                                            var que = QueueOperation(null, IQueueType.DeQueue); if (que.First().Key > 0) { // 判斷該代理IP時間在5分鐘內產生的直接返回使用
                                                if ((que.First().Value.CreateTime.AddMinutes(5)) > DateTime.Now) { Console.WriteLine("{0}> 直接輸出{1}", DateTime.Now.ToString("s"), que.First().Value.Id); // 輸出http響應代碼
 writer.WriteLine(que.First().Value.Id); QueueOperation(que.First().Value, IQueueType.EnQueue); break; } else { // 驗證代理IP有效性
                                                    if (DbVerIp(que.First().Value)) { Console.WriteLine("{0}> 驗證輸出{1}", DateTime.Now.ToString("s"), que.First().Value.Id); // 輸出http響應代碼
 writer.WriteLine(que.First().Value.Id); // 退出本次請求
                                                        break; } } } count++; // 隊列無可用代理IP狀況下等待2秒再獲取
                                            Thread.Sleep(TimeSpan.FromSeconds(2)); } } //writer.Close(); //ctx.Response.Close();
 } } catch (Exception ex) { try { Console.WriteLine("{0}> 接口異常:{1}", DateTime.Now.ToString("s"), ex.Message); using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream)) { ctx.Response.StatusCode = 200; writer.WriteLine("false"); } } catch (Exception e) { } } })).Start(); } })).Start(); } }

 

 

 

 

源碼 地址: https://github.com/Yahuiya/Proxyui

 

若是有什麼錯誤的,還請指出,哈哈哈哈哈url

相關文章
相關標籤/搜索