IPHelper.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. private List<Task> taskList = new List<Task>();
  20. static object locker = new object();
  21. private static List<string> list = new List<string>();
  22. private static List<string> urlList = new List<string>();
  23. private static string title;
  24. private static string iPAgencyAddress = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IPAgency.txt";
  25. /// <summary>
  26. /// 初始化方法
  27. /// </summary>
  28. public static void GetIp(IEnumerable<string> ipList = null, bool isIpAgency = true)
  29. {
  30. if (isIpAgency)
  31. {
  32. string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
  33. var urlDataList = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
  34. var list = from a in urlDataList
  35. select a.Url;
  36. //代理IP池
  37. new IPHelper().GetIPData(list.ToList(), "ip", iPAgencyAddress);
  38. }
  39. //爬取ip池
  40. if (ipList == null || ipList.Count() <= 0)
  41. ipList = new List<string> {
  42. "http://fenxi.zgzcw.com/1766186/dxdb/zhishu?company_id=8&company=Bet365",//大小指数-实时
  43. "http://fenxi.zgzcw.com/1766186/bjop/zhishu?company_id=115&company=%E5%A8%81%E5%BB%89%E5%B8%8C%E5%B0%94",//欧赔指数-实时
  44. "http://fenxi.zgzcw.com/1766186/ypdb/zhishu?company_id=1&company=%E6%BE%B3%E9%97%A8",//亚盘指数-实时
  45. "http://fenxi.zgzcw.com/2413445/dxdb5",//大小指数-固化
  46. "http://fenxi.zgzcw.com/2413445/bjop",//欧赔指数-固化
  47. "http://fenxi.zgzcw.com/2413445/ypdb",//亚盘指数-固化
  48. "http://saishi.zgzcw.com/soccer/team/25",//球队介绍
  49. "http://saishi.zgzcw.com/soccer",//赛事
  50. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxpl",//上下盘
  51. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxds",//上下单双
  52. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/jqds",//总进球单双
  53. "http://saishi.zgzcw.com/soccer/league/36/2018-2019/ssb",//射手榜
  54. "http://saishi.zgzcw.com/soccer/league/36/2018-2019",//积分榜
  55. "http://saishi.zgzcw.com/soccer/league/36",//球队,分组,比赛
  56. "http://cp.zgzcw.com/lottery/zucai/14csfc/index.jsp",//14场
  57. "http://cp.zgzcw.com/lottery/zucai/6cbqc/index.jsp",//6场
  58. "http://cp.zgzcw.com/lottery/zucai/4cjqc/index.jsp",//4场
  59. "http://live.zgzcw.com/jz/",//竞彩
  60. "http://live.zgzcw.com/bd/",//北单
  61. "http://live.zgzcw.com/sfc/",//足彩
  62. "http://fenxi.zgzcw.com/2404696/zrtj",//阵容
  63. "http://saishi.zgzcw.com/soccer/player/4369",//球员
  64. "http://nba.nowscore.com/League/index_cn.aspx?SclassID=5&MatchSeason=2017-2018",//CBA
  65. };
  66. new IPHelper().GetIPData(ipList.ToList());
  67. }
  68. private void GetIPData(List<string> _urlList, string _title = "", string path = "")
  69. {
  70. list = new List<string>();
  71. if (_urlList.Count <= 0)
  72. urlList.Add(ConfigurationManager.AppSettings["TestUrl"].ToString());
  73. else
  74. urlList = _urlList;
  75. title = _title;
  76. Trace.WriteLine("开始更新IP代理池!请稍后");
  77. string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
  78. var urlData = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
  79. urlData.ForEach(p =>
  80. {
  81. taskList.Add(Task.Run(() => GetIp(p)));
  82. });
  83. Thread.Sleep(300000);
  84. Task.WaitAll(taskList.ToArray());
  85. Trace.WriteLine("IP代理池更新完毕!可用IP:" + list.Count);
  86. if (path.IsEmpty())
  87. path = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IP.txt";
  88. if (list.Count > 0)
  89. CommonHelper.Write_IP(path, JsonConvert.SerializeObject(list.Distinct().ToList()));
  90. }
  91. /// <summary>
  92. /// 代理
  93. /// </summary>
  94. /// <param name="DATA"></param>
  95. private void GetIp(IPEntity model)
  96. {
  97. for (int i = 0; i < model.Number; i++)
  98. {
  99. var _url = model.Url;
  100. if (model.Number != 1)
  101. {
  102. if (model.Url.Split('?').Length > 1)
  103. _url = model.Url + "&" + model.PageName + "=" + (i + 1);
  104. else
  105. _url = model.Url + (i == 0 ? string.Empty : "/" + (i + 1));
  106. }
  107. var doc = new HtmlDocument();
  108. doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
  109. var number = 0;
  110. while (string.IsNullOrEmpty(doc.DocumentNode.InnerHtml))
  111. {
  112. if (number >= 20)
  113. break;
  114. doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
  115. number++;
  116. }
  117. var parents = model.SelectParents.Split(',').ToList();
  118. var trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
  119. number = 0;
  120. while (trparents == null)
  121. {
  122. if (number >= 20)
  123. break;
  124. doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
  125. trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
  126. number++;
  127. }
  128. if (trparents == null)
  129. return;
  130. var tr = trparents.SelectNodes(parents[1]);
  131. foreach (HtmlNode item in tr)
  132. {
  133. if (tr.IndexOf(item) != 0)
  134. {
  135. var td = item.SelectNodes(model.SelectParent);
  136. var path = model.SelectPath.Split(',').ToList();
  137. var ip = td[int.Parse(path[0])].InnerText + ":" + td[int.Parse(path[1])].InnerText;
  138. SetData(ip);
  139. }
  140. }
  141. }
  142. }
  143. /// <summary>
  144. /// Http请求
  145. /// </summary>
  146. /// <param name="uri"></param>
  147. /// <param name="proxy"></param>
  148. /// <returns></returns>
  149. public static string TestIp(Uri uri, string proxy = null)
  150. {
  151. var pageSource = string.Empty;
  152. try
  153. {
  154. var watch = new Stopwatch();
  155. watch.Start();
  156. var request = (HttpWebRequest)WebRequest.Create(uri);
  157. request.Accept = "text/html, */*; q=0.01";
  158. request.ServicePoint.Expect100Continue = false;//加快载入速度
  159. request.ServicePoint.UseNagleAlgorithm = false;//禁止Nagle算法加快载入速度
  160. request.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
  161. request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
  162. request.ContentType = "text/html;charset=UTF-8";//定义文档类型及编码
  163. request.AllowAutoRedirect = true;//禁止自动跳转
  164. //设置User-Agent,伪装成Google Chrome浏览器
  165. request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36";
  166. request.Timeout = 5000;//定义请求超时时间为5秒
  167. request.KeepAlive = true;//启用长连接
  168. request.Method = "GET";//定义请求方式为GET
  169. request.ReadWriteTimeout = 10000;
  170. if (proxy != null) request.Proxy = new WebProxy(proxy);//设置代理服务器IP,伪装请求地址
  171. //request.CookieContainer = this.CookiesContainer;//附加Cookie容器
  172. request.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
  173. using (var response = (HttpWebResponse)request.GetResponse())
  174. {//获取请求响应
  175. // foreach (Cookie cookie in response.Cookies) this.CookiesContainer.Add(cookie);//将Cookie加入容器,保存登录状态
  176. if (response.ContentEncoding.ToLower().Contains("gzip"))//解压
  177. {
  178. using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
  179. {
  180. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  181. {
  182. pageSource = reader.ReadToEnd();
  183. }
  184. }
  185. }
  186. else if (response.ContentEncoding.ToLower().Contains("deflate"))//解压
  187. {
  188. using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
  189. {
  190. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  191. {
  192. pageSource = reader.ReadToEnd();
  193. }
  194. }
  195. }
  196. else
  197. {
  198. using (Stream stream = response.GetResponseStream())//原始
  199. {
  200. using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
  201. {
  202. pageSource = reader.ReadToEnd();
  203. }
  204. }
  205. }
  206. }
  207. request.Abort();
  208. watch.Stop();
  209. var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;//获取当前任务线程ID
  210. var milliseconds = watch.ElapsedMilliseconds;//获取请求执行时间
  211. return pageSource;
  212. }
  213. catch (Exception ex)
  214. {
  215. //Trace.WriteLine("连接失败:" + proxy + "||" + ex.Message);
  216. return string.Empty;
  217. }
  218. }
  219. /// <summary>
  220. /// 获取数据
  221. /// </summary>
  222. /// <param name="ip"></param>
  223. /// <returns></returns>
  224. private async void SetData(string ip)
  225. {
  226. taskList.Add(Task.Run(() =>
  227. {
  228. Thread.Sleep(100);
  229. try
  230. {
  231. var url = urlList[new Random().Next(0, urlList.Count)];
  232. Trace.WriteLine("url:" + url);
  233. var html = "";
  234. if (url.ToLower().Contains("nba.nowscore"))
  235. html = new HttpHelper().GetHtml(new HttpItem { Url = url, Timeout = 10 * 1000, Method = "GET", Allowautoredirect = true, ReadWriteTimeout = 10000, ProxyIp =ip }).Html;
  236. else
  237. // var html = TestIp(new Uri(url), ip);
  238. html = new HttpHelper().GetHtml(new HttpItem { Url = url, Timeout = 10 * 1000, Method = "GET",ReadWriteTimeout= 10000 ,ProxyIp = ip }).Html;
  239. var doc = new HtmlDocument();
  240. if (!string.IsNullOrEmpty(html))
  241. {
  242. var _title = title;
  243. if (url.ToLower().Contains("nba.nowscore"))
  244. _title = "捷豹";
  245. doc.LoadHtml(html);
  246. var body = doc.DocumentNode.SelectNodes(".//body");
  247. if ((!url.ToLower().Contains("nba.nowscore") && (body == null || string.IsNullOrEmpty(body[0].InnerHtml)))
  248. || (html.Contains("403") && html.ToLower().Contains("forbidden"))
  249. || (html.Contains("404") && html.ToLower().Contains("not found"))
  250. || (!string.IsNullOrEmpty(_title) && !html.ToLower().Contains(_title)))
  251. {
  252. }
  253. else
  254. {
  255. lock (locker)
  256. {
  257. list.Add(ip);
  258. }
  259. Trace.WriteLine("连接成功:" + ip);
  260. Console.WriteLine(ip);
  261. }
  262. }
  263. else
  264. {
  265. //Trace.WriteLine("连接失败:" + ip);
  266. }
  267. }
  268. finally
  269. {
  270. }
  271. }));
  272. }
  273. }
  274. public class IPEntity
  275. {
  276. /// <summary>
  277. /// 父节点,,也就是ip的父节点
  278. /// 最后一个为SelectNodes,之前的为SelectSingleNode
  279. /// </summary>
  280. public string SelectParents { get; set; }
  281. /// <summary>
  282. /// 路径
  283. /// </summary>
  284. public string Url { get; set; }
  285. /// <summary>
  286. /// 上一级的名称(td||th)
  287. /// </summary>
  288. public string SelectParent { get; set; } = "td";
  289. /// <summary>
  290. /// 最终Ip的路径 (ip和host)
  291. /// </summary>
  292. public string SelectPath { get; set; }
  293. /// <summary>
  294. /// 查询页数
  295. /// </summary>
  296. public int Number { get; set; }
  297. /// <summary>
  298. /// 匿名路径
  299. /// </summary>
  300. public int AnonymityPath { get; set; } = -1;
  301. /// <summary>
  302. /// 分页参数名称
  303. /// </summary>
  304. public string PageName { get; set; }
  305. }
  306. }