123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336 |
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Diagnostics;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using HtmlAgilityPack;
- using Newtonsoft.Json;
- using static System.Net.Mime.MediaTypeNames;
- namespace FCS.Common
- {
- public class IPHelper
- {
- private List<Task> taskList = new List<Task>();
- static object locker = new object();
- private static List<string> list = new List<string>();
- private static List<string> urlList = new List<string>();
- private static string title;
- private static string iPAgencyAddress = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IPAgency.txt";
- /// <summary>
- /// 初始化方法
- /// </summary>
- public static void GetIp(IEnumerable<string> ipList = null, bool isIpAgency = true)
- {
- if (isIpAgency)
- {
- string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
- var urlDataList = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
- var list = from a in urlDataList
- select a.Url;
- //代理IP池
- new IPHelper().GetIPData(list.ToList(), "ip", iPAgencyAddress);
- }
- //爬取ip池
- if (ipList == null || ipList.Count() <= 0)
- ipList = new List<string> {
- "http://fenxi.zgzcw.com/1766186/dxdb/zhishu?company_id=8&company=Bet365",//大小指数-实时
- "http://fenxi.zgzcw.com/1766186/bjop/zhishu?company_id=115&company=%E5%A8%81%E5%BB%89%E5%B8%8C%E5%B0%94",//欧赔指数-实时
- "http://fenxi.zgzcw.com/1766186/ypdb/zhishu?company_id=1&company=%E6%BE%B3%E9%97%A8",//亚盘指数-实时
- "http://fenxi.zgzcw.com/2413445/dxdb",//大小指数-固化
- "http://fenxi.zgzcw.com/2413445/bjop",//欧赔指数-固化
- "http://fenxi.zgzcw.com/2413445/ypdb",//亚盘指数-固化
- "http://saishi.zgzcw.com/soccer/team/25",//球队介绍
- "http://saishi.zgzcw.com/soccer",//赛事
- "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxpl",//上下盘
- "http://saishi.zgzcw.com/soccer/league/36/2018-2019/sxds",//上下单双
- "http://saishi.zgzcw.com/soccer/league/36/2018-2019/jqds",//总进球单双
- "http://saishi.zgzcw.com/soccer/league/36/2018-2019/ssb",//射手榜
- "http://saishi.zgzcw.com/soccer/league/36/2018-2019",//积分榜
- "http://saishi.zgzcw.com/soccer/league/36",//球队,分组,比赛
- "http://cp.zgzcw.com/lottery/zucai/14csfc/index.jsp",//14场
- "http://cp.zgzcw.com/lottery/zucai/6cbqc/index.jsp",//6场
- "http://cp.zgzcw.com/lottery/zucai/4cjqc/index.jsp",//4场
- "http://live.zgzcw.com/jz/",//竞彩
- "http://live.zgzcw.com/bd/",//北单
- "http://live.zgzcw.com/sfc/",//足彩
- "http://fenxi.zgzcw.com/2404696/zrtj",//阵容
- "http://saishi.zgzcw.com/soccer/player/4369",//球员
- "http://nba.nowscore.com/League/index_cn.aspx?SclassID=5&MatchSeason=2017-2018",//CBA
- "http://www.500.com"
- };
- new IPHelper().GetIPData(ipList.ToList());
- }
- private void GetIPData(List<string> _urlList, string _title = "", string path = "")
- {
- list = new List<string>();
- if (_urlList.Count <= 0)
- urlList.Add(ConfigurationManager.AppSettings["TestUrl"].ToString());
- else
- urlList = _urlList;
- title = _title;
- Trace.WriteLine("开始更新IP代理池!请稍后");
- string configFile = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/UrlData.xml";
- var urlData = CommonHelper.ConvertXMLToObject<IPEntity>(configFile, "UrlSetting");
- urlData.ForEach(p =>
- {
- taskList.Add(Task.Run(() => GetIp(p)));
- });
- Thread.Sleep(300000);
- Task.WaitAll(taskList.ToArray());
- Trace.WriteLine("IP代理池更新完毕!可用IP:" + list.Count);
- if (path.IsEmpty())
- path = AppDomain.CurrentDomain.BaseDirectory + "/XmlConfig/IP.txt";
- if (list.Count > 0)
- CommonHelper.Write_IP(path, JsonConvert.SerializeObject(list.Distinct().ToList()));
- }
- /// <summary>
- /// 代理
- /// </summary>
- /// <param name="DATA"></param>
- private void GetIp(IPEntity model)
- {
- for (int i = 0; i < model.Number; i++)
- {
- var _url = model.Url;
- if (model.Number != 1)
- {
- if (model.Url.Split('?').Length > 1)
- _url = model.Url + "&" + model.PageName + "=" + (i + 1);
- else
- _url = model.Url + (i == 0 ? string.Empty : "/" + (i + 1));
- }
- var doc = new HtmlDocument();
- doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
- var number = 0;
- while (string.IsNullOrEmpty(doc.DocumentNode.InnerHtml))
- {
- if (number >= 20)
- break;
- doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
- number++;
- }
- var parents = model.SelectParents.Split(',').ToList();
- var trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
- number = 0;
- while (trparents == null)
- {
- if (number >= 20)
- break;
- doc.LoadHtml(new HttpHelper().GetHtml(new HttpItem { Url = _url, Timeout = 10 * 1000, Method = "GET", ReadWriteTimeout = 10000, ProxyIp = CommonHelper.GetIp(iPAgencyAddress, false) }).Html);
- trparents = doc.DocumentNode.SelectSingleNode(parents[0]);
- number++;
- }
- if (trparents == null)
- return;
- var tr = trparents.SelectNodes(parents[1]);
- foreach (HtmlNode item in tr)
- {
- if (tr.IndexOf(item) != 0)
- {
- var td = item.SelectNodes(model.SelectParent);
- if (td!=null)
- {
- var path = model.SelectPath.Split(',').ToList();
- var ip = td[int.Parse(path[0])].InnerText;
- if (path.Count == 2)
- {
- ip = td[int.Parse(path[0])].InnerText + ":" + td[int.Parse(path[1])].InnerText;
- }
- SetData(ip);
- }
-
- }
- }
- }
- }
- /// <summary>
- /// Http请求
- /// </summary>
- /// <param name="uri"></param>
- /// <param name="proxy"></param>
- /// <returns></returns>
- public static string TestIp(Uri uri, string proxy = null)
- {
- var pageSource = string.Empty;
- try
- {
- var watch = new Stopwatch();
- watch.Start();
- var request = (HttpWebRequest)WebRequest.Create(uri);
- request.Accept = "text/html, */*; q=0.01";
- request.ServicePoint.Expect100Continue = false;//加快载入速度
- request.ServicePoint.UseNagleAlgorithm = false;//禁止Nagle算法加快载入速度
- request.AllowWriteStreamBuffering = false;//禁止缓冲加快载入速度
- request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");//定义gzip压缩页面支持
- request.ContentType = "text/html;charset=UTF-8";//定义文档类型及编码
- request.AllowAutoRedirect = true;//禁止自动跳转
- //设置User-Agent,伪装成Google Chrome浏览器
- request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36";
- request.Timeout = 5000;//定义请求超时时间为5秒
- request.KeepAlive = true;//启用长连接
- request.Method = "GET";//定义请求方式为GET
- request.ReadWriteTimeout = 10000;
- if (proxy != null) request.Proxy = new WebProxy(proxy);//设置代理服务器IP,伪装请求地址
- //request.CookieContainer = this.CookiesContainer;//附加Cookie容器
- request.ServicePoint.ConnectionLimit = int.MaxValue;//定义最大连接数
- using (var response = (HttpWebResponse)request.GetResponse())
- {//获取请求响应
- // foreach (Cookie cookie in response.Cookies) this.CookiesContainer.Add(cookie);//将Cookie加入容器,保存登录状态
- if (response.ContentEncoding.ToLower().Contains("gzip"))//解压
- {
- using (GZipStream stream = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- pageSource = reader.ReadToEnd();
- }
- }
- }
- else if (response.ContentEncoding.ToLower().Contains("deflate"))//解压
- {
- using (DeflateStream stream = new DeflateStream(response.GetResponseStream(), CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- pageSource = reader.ReadToEnd();
- }
- }
- }
- else
- {
- using (Stream stream = response.GetResponseStream())//原始
- {
- using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
- {
- pageSource = reader.ReadToEnd();
- }
- }
- }
- }
- request.Abort();
- watch.Stop();
- var threadId = System.Threading.Thread.CurrentThread.ManagedThreadId;//获取当前任务线程ID
- var milliseconds = watch.ElapsedMilliseconds;//获取请求执行时间
- return pageSource;
- }
- catch (Exception ex)
- {
- //Trace.WriteLine("连接失败:" + proxy + "||" + ex.Message);
- return string.Empty;
- }
- }
- /// <summary>
- /// 获取数据
- /// </summary>
- /// <param name="ip"></param>
- /// <returns></returns>
- private async void SetData(string ip)
- {
- taskList.Add(Task.Run(() =>
- {
- Thread.Sleep(100);
- try
- {
- var url = urlList[new Random().Next(0, urlList.Count)];
- Trace.WriteLine("url:" + url);
- var html = "";
- if (url.ToLower().Contains("nba.nowscore"))
- html = new HttpHelper().GetHtml(new HttpItem { Url = url, Timeout = 10 * 1000, Method = "GET", Allowautoredirect = true, ReadWriteTimeout = 10000, ProxyIp =ip }).Html;
- else
- // var html = TestIp(new Uri(url), ip);
- html = new HttpHelper().GetHtml(new HttpItem { Url = url, Timeout = 10 * 1000, Method = "GET",ReadWriteTimeout= 10000 ,ProxyIp = ip }).Html;
- var doc = new HtmlDocument();
- if (!string.IsNullOrEmpty(html))
- {
- var _title = title;
- if (url.ToLower().Contains("nba.nowscore"))
- _title = "捷豹";
- doc.LoadHtml(html);
- var body = doc.DocumentNode.SelectNodes(".//body");
- if ((!url.ToLower().Contains("nba.nowscore") && (body == null || string.IsNullOrEmpty(body[0].InnerHtml)))
- || (html.Contains("403") && html.ToLower().Contains("forbidden"))
- || (html.Contains("404") && html.ToLower().Contains("not found"))
- || (!string.IsNullOrEmpty(_title) && !html.ToLower().Contains(_title)))
- {
- }
- else
- {
- lock (locker)
- {
- list.Add(ip);
- }
- Trace.WriteLine("连接成功:" + ip);
- Console.WriteLine(ip);
- }
- }
- else
- {
- //Trace.WriteLine("连接失败:" + ip);
- }
- }
- finally
- {
- }
- }));
- }
- }
- public class IPEntity
- {
- /// <summary>
- /// 父节点,,也就是ip的父节点
- /// 最后一个为SelectNodes,之前的为SelectSingleNode
- /// </summary>
- public string SelectParents { get; set; }
- /// <summary>
- /// 路径
- /// </summary>
- public string Url { get; set; }
- /// <summary>
- /// 上一级的名称(td||th)
- /// </summary>
- public string SelectParent { get; set; } = "td";
- /// <summary>
- /// 最终Ip的路径 (ip和host)
- /// </summary>
- public string SelectPath { get; set; }
- /// <summary>
- /// 查询页数
- /// </summary>
- public int Number { get; set; }
- /// <summary>
- /// 匿名路径
- /// </summary>
- public int AnonymityPath { get; set; } = -1;
- /// <summary>
- /// 分页参数名称
- /// </summary>
- public string PageName { get; set; }
- }
- }
|