IPHelper.cs 15 KB

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