IPHelper.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Diagnostics;
  5. using System.IO;
  6. using System.IO.Compression;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using HtmlAgilityPack;
  13. using Newtonsoft.Json;
  14. using static System.Net.Mime.MediaTypeNames;
  15. namespace FCS.Common
  16. {
  17. public class IPHelper
  18. {
  19. static object locker = new object();
  20. static int threadCount = 0;
  21. static int finishcount = 0;
  22. private static List<string> list = new List<string>();
  23. private static List<string> listContent = new List<string>();
  24. private static List<string> urlList = new List<string>();
  25. private static string title;
  26. private static bool isSeleteOne = false;
  27. private static int dateNowMinute = DateTime.Now.Minute;
  28. private static string iPAgencyAddress = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IPAgency.txt";
  29. public static Dictionary<string, string> formDataDict;
  30. /// <summary>
  31. /// 初始化方法
  32. /// </summary>
  33. public static void GetIp(IEnumerable<string> ipList = null, bool isIpAgency = true)
  34. {
  35. if (isIpAgency)
  36. {
  37. string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
  38. var urlDataList = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
  39. var list = from a in urlDataList
  40. select a.Url;
  41. //代理IP池
  42. GetIPData(list.ToList(), "ip", iPAgencyAddress);
  43. }
  44. //爬取ip池
  45. if (ipList == null || ipList.Count() <= 0)
  46. ipList = new List<string> {
  47. "http://fenxi.zgzcw.com/1766186/dxdb/zhishu?company_id=8&company=Bet365",//大小指数-实时
  48. "http://fenxi.zgzcw.com/1766186/bjop/zhishu?company_id=115&company=%E5%A8%81%E5%BB%89%E5%B8%8C%E5%B0%94",//欧赔指数-实时
  49. "http://fenxi.zgzcw.com/1766186/ypdb/zhishu?company_id=1&company=%E6%BE%B3%E9%97%A8",//亚盘指数-实时
  50. "http://fenxi.zgzcw.com/2413445/dxdb5",//大小指数-固化
  51. "http://fenxi.zgzcw.com/2413445/bjop",//欧赔指数-固化
  52. "http://fenxi.zgzcw.com/2413445/ypdb",//亚盘指数-固化
  53. "http://saishi.zgzcw.com/soccer/team/25",//球队介绍
  54. "http://saishi.zgzcw.com/soccer",//赛事
  55. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxpl",//上下盘
  56. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxds",//上下单双
  57. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/jqds",//总进球单双
  58. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/ssb",//射手榜
  59. "http://saishi.zgzcw.com/soccer/league/36/2018-2019",//积分榜
  60. "http://saishi.zgzcw.com/soccer/league/36",//球队,分组,比赛
  61. "http://cp.zgzcw.com/lottery/zucai/14csfc/index.jsp",//14场
  62. "http://cp.zgzcw.com/lottery/zucai/6cbqc/index.jsp",//6场
  63. "http://cp.zgzcw.com/lottery/zucai/4cjqc/index.jsp",//4场
  64. "http://live.zgzcw.com/jz/",//竞彩
  65. "http://live.zgzcw.com/bd/",//北单
  66. "http://live.zgzcw.com/sfc/",//足彩
  67. "http://fenxi.zgzcw.com/2404696/zrtj",//阵容
  68. "http://saishi.zgzcw.com/soccer/player/4369",//球员
  69. };
  70. GetIPData(ipList.ToList());
  71. }
  72. private static void GetIPData(List<string> _urlList, string _title = "", string path = "")
  73. {
  74. if (_urlList.Count <= 0)
  75. urlList.Add(ConfigurationManager.AppSettings["TestUrl"].ToString());
  76. else
  77. urlList = _urlList;
  78. title = _title;
  79. Trace.WriteLine("开始更新IP代理池!请稍后");
  80. string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
  81. var urlData = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
  82. urlData.ForEach(p =>
  83. {
  84. Task.Run(() => GetIp(p));
  85. });
  86. Thread.Sleep(300000);
  87. lock (locker)
  88. {
  89. while (finishcount != threadCount)
  90. {
  91. Thread.Sleep(5000);
  92. Trace.WriteLine("已执行线程:" + finishcount + "||剩余线程:" + (threadCount - finishcount) + "可用IP数:" + list.Count);
  93. Monitor.Wait(locker);//等待
  94. }
  95. }
  96. Trace.WriteLine("IP代理池更新完毕!可用IP:" + list.Count);
  97. if (path.IsEmpty())
  98. path = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IP.txt";
  99. if (list.Count > 0)
  100. CommonHelper.Write_IP(path, JsonConvert.SerializeObject(list.Distinct().ToList()));
  101. }
  102. public static string GetIPDataBYOne_FormData(List<string> _urlList, Dictionary<string, string> formData, string _title = "")
  103. {
  104. InitIPHelper();
  105. formDataDict = formData;
  106. return GetIPDataBYOne(_urlList, _title, true);
  107. }
  108. public static string GetIPDataBYOne(List<string> _urlList, string _title = "", bool isFormData = false)
  109. {
  110. if (!isFormData)
  111. InitIPHelper();
  112. isSeleteOne = true;
  113. if (_urlList.Count <= 0)
  114. urlList.Add(ConfigurationManager.AppSettings["TestUrl"].ToString());
  115. else
  116. urlList = _urlList;
  117. title = _title;
  118. Trace.WriteLine("获取单个IP!请稍后");
  119. string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
  120. var urlData = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
  121. urlData.ForEach(p =>
  122. {
  123. Task.Run(() => GetIp(p));
  124. });
  125. var content = string.Empty;
  126. dateNowMinute = DateTime.Now.Minute;
  127. while (true)
  128. {
  129. if (list.Count >= 1)
  130. {
  131. lock (locker)
  132. {
  133. content = listContent[0];
  134. break;
  135. }
  136. }
  137. else
  138. {
  139. var minute = DateTime.Now.Minute;
  140. var poor = dateNowMinute > minute ? minute + 60 - dateNowMinute : minute - dateNowMinute;
  141. if (poor > 3 || finishcount > 2000)
  142. {
  143. if (finishcount == threadCount || finishcount > 2000)
  144. break;
  145. }
  146. }
  147. }
  148. return content;
  149. }
  150. public static void InitIPHelper()
  151. {
  152. formDataDict = null;
  153. finishcount = 0;
  154. threadCount = 0;
  155. list = new List<string>();
  156. listContent = new List<string>();
  157. urlList = new List<string>();
  158. dateNowMinute = DateTime.Now.Minute;
  159. }
  160. /// <summary>
  161. /// 代理
  162. /// </summary>
  163. /// <param name="DATA"></param>
  164. private static void GetIp(IPEntity model)
  165. {
  166. for (int i = 0; i < model.Number; i++)
  167. {
  168. var _url = model.Url;
  169. if (model.Number != 1)
  170. {
  171. if (model.Url.Split('?').Length > 1)
  172. _url = model.Url + "&" + model.PageName + "=" + (i + 1);
  173. else
  174. _url = model.Url + (i == 0 ? string.Empty : "/" + (i + 1));
  175. }
  176. var doc = new HtmlDocument();
  177. if (isSeleteOne && list.Count > 0)
  178. return;
  179. doc.LoadHtml(TestIp(new Uri(_url), CommonHelper.GetIp(iPAgencyAddress, false)));
  180. while (string.IsNullOrEmpty(doc.DocumentNode.InnerHtml))
  181. {
  182. if (isSeleteOne && list.Count > 0)
  183. return;
  184. doc.LoadHtml(TestIp(new Uri(_url), CommonHelper.GetIp(iPAgencyAddress, false)));
  185. }
  186. var parents = model.SelectParents.Split(',').ToList();
  187. var trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
  188. while (trparents == null)
  189. {
  190. if (isSeleteOne && list.Count > 0)
  191. return;
  192. doc.LoadHtml(TestIp(new Uri(_url), CommonHelper.GetIp(iPAgencyAddress, false)));
  193. trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
  194. }
  195. var tr = trparents.SelectNodes(parents[1]);
  196. threadCount += tr.Count - 1;
  197. foreach (HtmlNode item in tr)
  198. {
  199. if (tr.IndexOf(item) != 0)
  200. {
  201. var td = item.SelectNodes(model.SelectParent);
  202. //if (model.AnonymityPath != -1)
  203. // if (td[model.AnonymityPath].InnerText.IndexOf("匿") != -1)
  204. // continue;
  205. var path = model.SelectPath.Split(',').ToList();
  206. var ip = td[int.Parse(path[0])].InnerText + ":" + td[int.Parse(path[1])].InnerText;
  207. if (isSeleteOne && list.Count > 0)
  208. return;
  209. SetData(ip);
  210. }
  211. }
  212. }
  213. }
  214. /// <summary>
  215. /// 异步创建爬虫
  216. /// </summary>
  217. /// <param name="uri">爬虫URL地址</param>
  218. /// <param name="proxy">代理服务器</param>
  219. /// <returns>网页源代码</returns>
  220. public static string TestIp(Uri uri, string proxy = null)
  221. {
  222. var pageSource = string.Empty;
  223. try
  224. {
  225. var watch = new Stopwatch();
  226. watch.Start();
  227. var request = (HttpWebRequest)WebRequest.Create(uri);
  228. request.Accept = "text/html, */*; q=0.01";
  229. request.ServicePoint.Expect100Continue = false;//加快载入速度
  230. request.ServicePoint.UseNagleAlgorithm = false;//禁止Nagle算法加快载入速度
  231. request.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
  232. request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
  233. request.ContentType = "text/html;charset=UTF-8";//定义文档类型及编码
  234. request.AllowAutoRedirect = false;//禁止自动跳转
  235. //设置User-Agent,伪装成Google Chrome浏览器
  236. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36";
  237. request.Timeout = 5000;//定义请求超时时间为5秒
  238. request.KeepAlive = true;//启用长连接
  239. request.Method = "GET";//定义请求方式为GET
  240. request.ReadWriteTimeout = 10000;
  241. if (proxy != null) request.Proxy = new WebProxy(proxy);//设置代理服务器IP,伪装请求地址
  242. //request.CookieContainer = this.CookiesContainer;//附加Cookie容器
  243. request.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
  244. using (var response = (HttpWebResponse)request.GetResponse())
  245. {//获取请求响应
  246. // foreach (Cookie cookie in response.Cookies) this.CookiesContainer.Add(cookie);//将Cookie加入容器,保存登录状态
  247. if (response.ContentEncoding.ToLower().Contains("gzip"))//解压
  248. {
  249. using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
  250. {
  251. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  252. {
  253. pageSource = reader.ReadToEnd();
  254. }
  255. }
  256. }
  257. else if (response.ContentEncoding.ToLower().Contains("deflate"))//解压
  258. {
  259. using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
  260. {
  261. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  262. {
  263. pageSource = reader.ReadToEnd();
  264. }
  265. }
  266. }
  267. else
  268. {
  269. using (Stream stream = response.GetResponseStream())//原始
  270. {
  271. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  272. {
  273. pageSource = reader.ReadToEnd();
  274. }
  275. }
  276. }
  277. }
  278. request.Abort();
  279. watch.Stop();
  280. var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;//获取当前任务线程ID
  281. var milliseconds = watch.ElapsedMilliseconds;//获取请求执行时间
  282. return pageSource;
  283. }
  284. catch (Exception ex)
  285. {
  286. //Trace.WriteLine("连接失败:" + proxy + "||" + ex.Message);
  287. return string.Empty;
  288. }
  289. }
  290. public static string TestIpFormDta(string uri, string proxy = null)
  291. {
  292. var pageSource = string.Empty;
  293. try
  294. {
  295. var watch = new Stopwatch();
  296. watch.Start();
  297. var request = (HttpWebRequest)WebRequest.Create(uri);
  298. request.Accept = "text/html, */*; q=0.01";
  299. request.ServicePoint.Expect100Continue = false;//加快载入速度
  300. request.ServicePoint.UseNagleAlgorithm = false;//禁止Nagle算法加快载入速度
  301. request.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
  302. request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
  303. request.ContentType = "application/x-www-form-urlencoded";//定义文档类型及编码
  304. request.AllowAutoRedirect = false;//禁止自动跳转
  305. //设置User-Agent,伪装成Google Chrome浏览器
  306. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36";
  307. request.Timeout = 5000;//定义请求超时时间为5秒
  308. request.KeepAlive = true;//启用长连接
  309. request.Method = "Post";//定义请求方式为GET
  310. request.ReadWriteTimeout = 10000;
  311. if (proxy != null) request.Proxy = new WebProxy(proxy);//设置代理服务器IP,伪装请求地址
  312. //request.CookieContainer = this.CookiesContainer;//附加Cookie容器
  313. request.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
  314. string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
  315. request.ContentType = "multipart/form-data; boundary=" + boundary;
  316. //验证在得到结果时是否有传入数据
  317. if (!request.Method.Trim().ToLower().Contains("get"))
  318. {
  319. MemoryStream stream = new MemoryStream();
  320. string format = "--" + boundary + "\r\nContent-Disposition:form-data;name=\"{0}\"\r\n\r\n{1}\r\n"; //自带项目分隔符
  321. foreach (string key in formDataDict.Keys)
  322. {
  323. string s = string.Format(format, key, formDataDict[key]);
  324. byte[] data = Encoding.UTF8.GetBytes(s);
  325. stream.Write(data, 0, data.Length);
  326. }
  327. byte[] foot_data = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n"); //项目最后的分隔符字符串需要带上--
  328. stream.Write(foot_data, 0, foot_data.Length);
  329. request.ContentLength = stream.Length;
  330. Stream requestStream = request.GetRequestStream(); //写入请求数据
  331. stream.Position = 0L;
  332. stream.CopyTo(requestStream);
  333. stream.Close();
  334. }
  335. using (var response = (HttpWebResponse)request.GetResponse())
  336. {//获取请求响应
  337. // foreach (Cookie cookie in response.Cookies) this.CookiesContainer.Add(cookie);//将Cookie加入容器,保存登录状态
  338. if (response.ContentEncoding.ToLower().Contains("gzip"))//解压
  339. {
  340. using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
  341. {
  342. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  343. {
  344. pageSource = reader.ReadToEnd();
  345. }
  346. }
  347. }
  348. else if (response.ContentEncoding.ToLower().Contains("deflate"))//解压
  349. {
  350. using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
  351. {
  352. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  353. {
  354. pageSource = reader.ReadToEnd();
  355. }
  356. }
  357. }
  358. else
  359. {
  360. using (Stream stream = response.GetResponseStream())//原始
  361. {
  362. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  363. {
  364. pageSource = reader.ReadToEnd();
  365. }
  366. }
  367. }
  368. }
  369. request.Abort();
  370. watch.Stop();
  371. var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;//获取当前任务线程ID
  372. var milliseconds = watch.ElapsedMilliseconds;//获取请求执行时间
  373. return pageSource;
  374. }
  375. catch (Exception ex)
  376. {
  377. //Trace.WriteLine("连接失败:" + proxy + "||" + ex.Message);
  378. return string.Empty;
  379. }
  380. }
  381. /// <summary>
  382. /// 获取数据
  383. /// </summary>
  384. /// <param name="ip"></param>
  385. /// <returns></returns>
  386. private static async Task<string> SetData(string ip)
  387. {
  388. return await Task.Run(() =>
  389. {
  390. Thread.Sleep(100);
  391. try
  392. {
  393. if (isSeleteOne && list.Count > 0)
  394. { }
  395. else
  396. {
  397. var url = urlList[new Random().Next(0, urlList.Count)];
  398. Trace.WriteLine("url:" + url);
  399. var html = "";
  400. if (formDataDict != null)
  401. html = TestIpFormDta(url, ip);
  402. else
  403. html = TestIp(new Uri(url), ip);
  404. var doc = new HtmlDocument();
  405. if (!string.IsNullOrEmpty(html))
  406. {
  407. doc.LoadHtml(html);
  408. var body = doc.DocumentNode.SelectNodes(".//body");
  409. if ((formDataDict == null && (body == null || string.IsNullOrEmpty(body[0].InnerHtml))) || (html.Contains("403") && html.ToLower().Contains("forbidden"))
  410. || (html.Contains("404") && html.ToLower().Contains("not found"))
  411. || (!string.IsNullOrEmpty(title) && !html.ToLower().Contains(title)))
  412. {
  413. }
  414. else
  415. {
  416. if (isSeleteOne && list.Count > 0)
  417. return string.Empty;
  418. lock (locker)
  419. {
  420. list.Add(ip);
  421. if (isSeleteOne)
  422. listContent.Add(html);
  423. }
  424. Trace.WriteLine("连接成功:" + ip);
  425. Console.WriteLine(ip);
  426. }
  427. }
  428. else
  429. {
  430. //Trace.WriteLine("连接失败:" + ip);
  431. }
  432. }
  433. }
  434. catch (Exception)
  435. {
  436. }
  437. finally
  438. {
  439. lock (locker)
  440. {
  441. finishcount++;
  442. Monitor.Pulse(locker); //完成,通知等待队列,告知已完,执行下一个。
  443. }
  444. }
  445. return string.Empty;
  446. });
  447. }
  448. }
  449. public class IPEntity
  450. {
  451. /// <summary>
  452. /// 父节点,,也就是ip的父节点
  453. /// 最后一个为SelectNodes,之前的为SelectSingleNode
  454. /// </summary>
  455. public string SelectParents { get; set; }
  456. /// <summary>
  457. /// 路径
  458. /// </summary>
  459. public string Url { get; set; }
  460. /// <summary>
  461. /// 上一级的名称(td||th)
  462. /// </summary>
  463. public string SelectParent { get; set; } = "td";
  464. /// <summary>
  465. /// 最终Ip的路径 (ip和host)
  466. /// </summary>
  467. public string SelectPath { get; set; }
  468. /// <summary>
  469. /// 查询页数
  470. /// </summary>
  471. public int Number { get; set; }
  472. /// <summary>
  473. /// 匿名路径
  474. /// </summary>
  475. public int AnonymityPath { get; set; } = -1;
  476. /// <summary>
  477. /// 分页参数名称
  478. /// </summary>
  479. public string PageName { get; set; }
  480. }
  481. }