private Dictionary<string, GameInfo> GetSchedulesByWNBA(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webWNBA.Document == null || this.webWNBA.Document.Body == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); Dictionary<string, HtmlElement> doc = new Dictionary<string, HtmlElement>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; // 找到資料 if (this.webWNBA.Document.GetElementById("gamesLeft") != null) doc["Left"] = this.webWNBA.Document.GetElementById("gamesLeft"); if (this.webWNBA.Document.GetElementById("gamesRight") != null) doc["Right"] = this.webWNBA.Document.GetElementById("gamesRight"); #region 取得日期 foreach (HtmlElement div in this.webWNBA.Document.GetElementsByTagName("div")) { if (div.GetAttribute("className") == "key-dates key-dates_sc") { // 轉成日期失敗就往下處理 if (!DateTime.TryParse(div.GetElementsByTagName("h2")[0].InnerText.Replace("Scores for", "").Trim(), out gameDate)) { return null; } } } #endregion 取得日期 // 處理資料 foreach (HtmlElement game in this.webWNBA.Document.GetElementsByTagName("div")) { if (game.Id != null && game.Id.IndexOf("-gameHeader") != -1) { string webId = game.Id.Replace("-gameHeader", ""); // 時間錯誤就往下處理 if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + this.webWNBA.Document.GetElementById(webId + "-statusLine1").InnerText.Replace("ET", ""), out gameTime)) continue; GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = this.webWNBA.Document.GetElementById(webId + "-aNameOffset").InnerText; schedule.Home = this.webWNBA.Document.GetElementById(webId + "-hNameOffset").InnerText; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByBJ(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webBJ.Document == null || this.webBJ.Document.Body == null || this.webBJ.Document.GetElementById("contents") == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; // 處理資料 foreach (HtmlElement games in this.webBJ.Document.GetElementById("contents").GetElementsByTagName("table")) { foreach (HtmlElement game in games.GetElementsByTagName("tr")) { // 沒有資料就往下處理 if (game.GetElementsByTagName("th").Count != 1 || game.GetElementsByTagName("td").Count != 1) continue; string[] txt = game.GetElementsByTagName("th")[0].InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); string webId = game.GetElementsByTagName("td")[0].Id; // 資料錯誤就往下處理 if (txt.Length != 4) continue; if (string.IsNullOrEmpty(webId)) continue; // 判斷文字 if (txt[0].IndexOf("(") != -1) txt[0] = txt[0].Substring(0, txt[0].IndexOf("(")).Trim(); txt[0] = txt[0].Replace("月", "/").Replace("日", "").Trim(); // 轉換日期 if (DateTime.TryParse(txt[0], out gameDate) && DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + txt[1], out gameTime)) { txt = txt[2].Split(new string[] { "vs." }, StringSplitOptions.RemoveEmptyEntries); // 判斷隊伍 if (txt.Length == 2) { GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = txt[0]; schedule.Home = txt[1]; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } } } // 傳回 return schedules; }
/// <summary> /// 加入賽程列表 /// </summary> /// <param name="scheduleList">賽程列表</param> /// <param name="teamList">隊伍列表</param> /// <param name="info">賽程資訊</param> /// <param name="time">時間調整值</param> private void AddToSchedule(List<Schedule.Schedule> scheduleList, Dictionary<string, Team.Team> teamList, GameInfo info, int time) { // 建立 schedule 物件 Schedule.Schedule sc = new Schedule.Schedule() { AllianceID = info.AllianceID, FullGameTime = info.GameTime.AddHours(time), GameType = info.GameType, WebID = info.WebID, ControlStates = 2, // 自動操盤 GameStates = "X", // 未開賽 OrderBy = 0 }; string gameType = info.GameType.ToLower(); // Order By switch (gameType) { // MLB, NBA 排序置頂 case "bkus": case "bbus": sc.OrderBy = 1; break; } // 棒球(補賽) if (gameType.StartsWith("bb")) { // IsReschedule sc.IsReschedule = false; } string home = info.Home; string away = info.Away; // 主客隊互換 info.SwapTeam(ref home, ref away); // 取得隊伍編號 int? teamAID = (!teamList.ContainsKey(away)) ? null : teamList[away].ID; int? teamBID = (!teamList.ContainsKey(home)) ? null : teamList[home].ID; if (teamAID.HasValue && teamBID.HasValue) { sc.TeamAID = teamAID; sc.TeamBID = teamBID; } if (!scheduleList.Contains(sc)) { scheduleList.Add(sc); } }
/// <summary> /// 正規賽賽事資料處理 /// </summary> /// <param name="allianceID">聯盟編號</param> /// <param name="gameType">賽事種類</param> /// <param name="acH">是否主客互換</param> /// <param name="calendar">arenaCalendar HtmlWindow 物件</param> /// <param name="schedules">賽程資料</param> /// <returns>賽程資料</returns> private Dictionary<string, GameInfo> GetScheduleOnRegular(int allianceID, string gameType, bool acH, HtmlWindow calendar, Dictionary<string, GameInfo> schedules) { DateTime gameDate = DateTime.Now.AddDays(-100);//初始化 DateTime gameDate_old = DateTime.Now.AddDays(-100);//初始化 DateTime gameTime = DateTime.Now; WebClient client = new WebClient(); HtmlElementCollection dataDoc = calendar.Document.GetElementsByTagName("table"); // 資料 foreach (HtmlElement table in dataDoc) { HtmlElementCollection trDoc = table.GetElementsByTagName("tr"); // 沒有資料就往下處理 if (trDoc.Count <= 2) continue; if (string.IsNullOrEmpty(trDoc[0].InnerText) || !DateTime.TryParse(trDoc[0].InnerText, out gameDate)) continue; string html = String.Empty; foreach (HtmlElement tr in trDoc) { // 沒有資料就往下處理 if (string.IsNullOrEmpty(tr.InnerText)) continue; HtmlElementCollection td = tr.GetElementsByTagName("td"); string webId = null; bool isReschedule = false; #region 取得日期 if (td.Count == 1) { // 轉成日期失敗就往下處理 if (!DateTime.TryParse(tr.InnerText, out gameDate)) { continue; } else if (gameDate != gameDate_old) { gameDate_old = gameDate; html = GetScoreBoardWeb(gameDate, client); if (html != null && html.IndexOf("No games scheduled.") != -1) { //没有赛事 尝试去热身赛 html = GetScoreBoardWeb2(gameDate, client); } if (String.IsNullOrEmpty(html)) { continue; } } } #endregion #region 取得時間 if (td.Count < 6) continue; // 轉成時間失敗就往下處理 string dateTime = String.Format("{0:yyyy-MM-dd} {1}", gameDate, td[2].InnerText); if (!DateTime.TryParse(dateTime, out gameTime)) { continue; } #endregion #region 跟盤 ID // HtmlDocument HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); // 取得跟盤編號 string away = td[0].InnerText.Trim(); string home = td[1].InnerText.Trim(); webId = FindScheduleWebID(schedules, doc, ref away, ref home); // 沒有編號就往下處理 if (string.IsNullOrEmpty(webId)) continue; #endregion GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId, isReschedule) { AcH = acH, Away = away, Home = home }; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } // 傳回 return schedules; }
/// <summary> /// 季後賽賽事資料處理 /// </summary> /// <param name="allianceID">聯盟編號</param> /// <param name="gameType">賽事種類</param> /// <param name="acH">是否主客互換</param> /// <param name="schedules">賽程資料</param> /// <returns>賽程資料</returns> private Dictionary<string, GameInfo> GetScheduleOnPlayOffs(int allianceID, string gameType, bool acH, Dictionary<string, GameInfo> schedules) { DateTime gameDate = DateTime.Now.AddDays(-100);//初始化 DateTime gameDate_old = DateTime.Now.AddDays(-100);//初始化 DateTime gameTime = DateTime.Now; WebClient client = new WebClient(); SortedList<DateTime, List<PlayOff>> gameList = new SortedList<DateTime, List<PlayOff>>(); HtmlElementCollection dataDoc = this.webMLB.Document.GetElementsByTagName("table"); // 特殊日期格式處理 CultureInfo info = CultureInfo.CreateSpecificCulture("en-US"); info.DateTimeFormat.AbbreviatedMonthNames = new string[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec", "" }; // 資料 foreach (HtmlElement table in dataDoc) { string className = table.GetAttribute("className"); if (!className.Contains("data")) { continue; } HtmlElementCollection trDoc = table.GetElementsByTagName("tr"); // 沒有資料就往下處理 if (trDoc.Count <= 2) continue; foreach (HtmlElement tr in trDoc) { if (!tr.GetAttribute("className").Contains("row")) { continue; } // 沒有資料就往下處理 if (string.IsNullOrEmpty(tr.InnerText)) continue; HtmlElementCollection td = tr.GetElementsByTagName("td"); if (td.Count < 3) { continue; } #region 取得日期/時間 string date = td[0].InnerText.Trim().Replace(".", String.Empty).Replace("*", String.Empty).Replace("Thurs", "Thu"); string time = td[1].InnerText.Trim().Replace(".", String.Empty); // 待定賽事, 不處理 if ("TBD".Equals(time.ToUpper())) { continue; } // 轉成日期失敗就往下處理 if (!DateTime.TryParse(date, info, DateTimeStyles.None, out gameDate)) { continue; } // 如果時間格式不包含 am/pm, 預設補上 pm time = time.ToLower(); if (!time.Contains("am") && !time.Contains("pm")) { time = String.Format("{0} pm", time); } string dateTime = String.Format("{0:yyyy-MM-dd} {1}", gameDate, time); // 轉換時間失敗就往下處理 if (!DateTime.TryParse(dateTime, out gameTime)) { continue; } #endregion // 取得隊名 ( ex: Oakland at Kansas City ) // 2014.10.02 季後賽隊名的欄位有可能是顯示開賽場地 ( 欄位名為 MATCHUP=隊伍, SITE=場地 ) string away = String.Empty; string home = String.Empty; string[] temp = td[2].InnerText.Split(new string[] { "at" }, StringSplitOptions.RemoveEmptyEntries); if (temp.Length >= 2) { away = temp[0].Trim(); home = temp[1].Trim(); } // 依開賽日期加入賽事資料 List<PlayOff> playoffList = (gameList.ContainsKey(gameDate)) ? gameList[gameDate] : new List<PlayOff>(); PlayOff playoff = new PlayOff(gameTime, away, home) { OriginalGameDate = date, OriginalGameTime = time }; playoffList.Add(playoff); gameList[gameDate] = playoffList; } } foreach (KeyValuePair<DateTime, List<PlayOff>> pair in gameList) { // HtmlDocument HtmlAgilityPack.HtmlDocument doc = null; gameDate = pair.Key; List<PlayOff> playoffList = pair.Value; // 按開賽時間排序 playoffList.Sort((x, y) => { return Comparer<DateTime>.Default.Compare(x.GameTime, y.GameTime); }); if (gameDate != gameDate_old) { gameDate_old = gameDate; string html = GetScoreBoardWeb(gameDate, client); if (html != null && html.IndexOf("No games scheduled.") != -1) { //没有赛事 尝试去热身赛 html = GetScoreBoardWeb2(gameDate, client); } if (String.IsNullOrEmpty(html)) { continue; } doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(html); } foreach (PlayOff playoff in playoffList) { bool isReschedule = false; string away = playoff.Away; string home = playoff.Home; #region 跟盤 ID // 取得跟盤編號 string webId = FindScheduleWebID(schedules, doc, ref away, ref home, playoff.OriginalGameTime); // 沒有編號就往下處理 if (string.IsNullOrEmpty(webId)) continue; #endregion GameInfo schedule = new GameInfo(allianceID, gameType, playoff.GameTime, webId, isReschedule) { AcH = acH, Away = away, Home = home }; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByCPBL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webCPBL.Document == null || this.webCPBL.Document.Body == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); // 賽局編號(自訂) int gameNum = 0; string gameDateYear = null; string gameDateMonth = null; string sourceId = GetGameUseSourceID(allianceID, gameType); DateTime gameDate = DateTime.Now; #region 取得年份 HtmlElement yearDoc = this.webCPBL.Document.GetElementById("ctl00_cphBox_ddl_year"); // 判斷資料 if (yearDoc != null) { foreach (HtmlElement select in yearDoc.Children) { // 判斷選擇 if (select.GetAttribute("selected").ToLower().Equals("selected") || select.GetAttribute("selected").ToLower().Equals("true")) { gameDateYear = select.GetAttribute("value"); break; } } } // 沒有年份就離開 if (String.IsNullOrEmpty(gameDateYear)) { return null; } #endregion #region 取得月份 HtmlElement monthDoc = this.webCPBL.Document.GetElementById("ctl00_cphBox_ddl_month"); // 判斷資料 if (monthDoc != null) { foreach (HtmlElement select in monthDoc.Children) { // 判斷選擇 if (select.GetAttribute("selected").ToLower().Equals("selected") || select.GetAttribute("selected").ToLower().Equals("true")) { string[] tmp= select.GetAttribute("value").Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries); if (tmp.Length > 0) { gameDateMonth = tmp[0]; break; } } } } // 沒有月份就離開 if (String.IsNullOrEmpty(gameDateMonth)) { return null; } #endregion #region 取得資料 // 取出 class="day" 起始的 table (表示每日賽程的 table) List<HtmlElement> tableList = (from HtmlElement tb in this.webCPBL.Document.GetElementsByTagName("table") where tb.GetAttribute("className").StartsWith("day") == true select tb).ToList<HtmlElement>(); foreach (HtmlElement table in tableList) { var trList = table.Children[0].Children.Cast<HtmlElement>().ToList<HtmlElement>(); // 沒有比賽, 不處理 if (trList.Count <= 1) { continue; } // 取得日期 HtmlElement trDate = trList[0]; string gameDateStr = String.Format("{0}/{1}/{2}", gameDateYear, gameDateMonth, trDate.Children[0].InnerText); // 轉成日期失敗就往下處理 if (!DateTime.TryParse(gameDateStr, out gameDate)) { continue; } // 找到隊伍標籤 List<HtmlElement> trTeamList = (from HtmlElement tr in trList where tr.GetAttribute("className").Equals("team") == true select tr).ToList<HtmlElement>(); // 當日沒賽事, 不處理 if (trTeamList.Count == 0) { continue; } foreach (HtmlElement trTeam in trTeamList) { string teamAway = null; string teamHome = null; DateTime gameTime = DateTime.Now; string webId = null; HtmlElementCollection imgTeam = trTeam.GetElementsByTagName("img"); // 僅有一隊, 不處理 if (imgTeam.Count < 2) { continue; } for (int i=0; i < imgTeam.Count; i++) { string src = imgTeam[i].GetAttribute("src"); // 僅取得圖片名稱 int idx = src.LastIndexOf("/"); src = src.Substring((idx + 1), src.Length - (idx + 1)); // 隊伍:左客右主(先抓到的項目為客隊) if (i == 0) { teamAway = src; } else { teamHome = src; } } // tr[class='game'] 取得比賽資訊 int teamIdx = trList.IndexOf(trTeam); if (teamIdx >= trList.Count) { continue; } HtmlElement trGame = trList[teamIdx + 1]; // 找不到比賽資訊, 不處理 if (trGame == null) { continue; } HtmlElement tbGameInfo = (from HtmlElement tb in trGame.GetElementsByTagName("table") select tb).DefaultIfEmpty(null).FirstOrDefault(); // 找不到比賽資訊, 不處理 if (tbGameInfo == null) { continue; } // tr[class='normal'] 取得 WebID 節點 HtmlElementCollection trGameInfoList = tbGameInfo.Children[0].Children; HtmlElementCollection child = trGameInfoList[0].Children; if (child.Count > 0) { HtmlElement tbWebId = child[0]; HtmlElementCollection thColl = tbWebId.GetElementsByTagName("th"); if (thColl.Count == 3) { // WebId //webId = thColl[1].InnerText; } } // tr 取得時間節點 child = trGameInfoList[1].Children; if (child.Count > 0) { HtmlElement tbGameTime = child[0]; HtmlElementCollection tdColl =tbGameTime.GetElementsByTagName("td"); if (tdColl.Count == 3) { HtmlElement tdTime = tdColl[1]; // 時間 <td> 下還有 element: 比賽結束 往下處理 if (tdTime.Children.Count > 0) { continue; } string timeStr = tdTime.InnerText; string dateTime = String.Format("{0:yyyy/MM/dd} {1}", gameDate, timeStr); // 若無法解析比賽時間, 往下處理 if (!DateTime.TryParse(dateTime, out gameTime)) { continue; } } else { continue; } } else { continue; } gameNum++; // 產生賽程物件 GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId) { Away = teamAway, Home = teamHome, SourceID = sourceId, AcH = acH }; string key = gameNum.ToString(); schedules[key] = schedule; } } #endregion // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByNCAA(int allianceID, string gameType, bool acH = false) { string sourceId = GetGameUseSourceID(allianceID, gameType); Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime startDate = dtpNCAASDate.Value.Date; DateTime endDate = dtpNCAAEDate.Value.Date; WebClient w = new WebClient(); while (startDate <= endDate) { string url = String.Format(@"http://data.ncaa.com/jsonp/scoreboard/basketball-men/d1/{0}/{1:00}/{2:00}/scoreboard.html", startDate.Year, startDate.Month, startDate.Day); // 設定下一日 startDate = startDate.AddDays(1); string data= String.Empty; try { data = w.DownloadString(url); } catch { continue; } if (!String.IsNullOrEmpty(data)) { try { // 取得 json 資料 data = data.Replace(data.Substring(0, data.IndexOf("{")), "") .Replace(data.Substring(data.LastIndexOf("}") + 1), ""); JObject obj = JsonConvert.DeserializeObject<JObject>(data); JArray array = obj["scoreboard"] as JArray; if (array != null) { JObject scoreboard = array[0] as JObject; JArray games = scoreboard["games"] as JArray; // 賽程資料 if (games != null) { foreach (JObject game in games) { string comment = String.Empty; string webID = game["id"].ToString(); string gameState = game["gameState"].ToString().ToLower(); // 賽程結束, 不處理 if (gameState.Equals("final")) { continue; } string date = game["startDate"].ToString(); string time = game["startTime"].ToString().ToUpper(); // 賽程時間未定, 標記訊息 if (time.Equals("TBA")) { comment = "(尚未確認開賽時間,賽事暫時無法建立)"; } //// 取得 Utc 紀元時間 //double epoch = Convert.ToDouble(game["startTimeEpoch"].ToString()); //DateTime gameTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(epoch); string [] strTime=time.Split(' '); if (strTime.Length>=3) { if (strTime[1]=="PM") { DateTime dateTemp= (Convert.ToDateTime(date+" "+strTime[0]).AddHours(12)); gameTime = dateTemp.AddHours(13); } else if (strTime[1] == "AM") { DateTime dateTemp = (Convert.ToDateTime(date + " " + strTime[0])); gameTime = dateTemp.AddHours(13); } } string home = String.Empty; string away = String.Empty; //主場隊伍 JObject teamHome = game["home"] as JObject; if (teamHome != null) { home = teamHome["nameRaw"].ToString(); } //客場對伍 JObject teamAway = game["away"] as JObject; if (teamAway != null) { away = teamAway["nameRaw"].ToString(); } //若主隊或客隊是空值, 不處理 if (String.IsNullOrEmpty(home) || String.IsNullOrEmpty(away)) { continue; } GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webID) { Home = home, Away = away, SourceID = sourceId, AcH = acH, Comment = comment }; schedules[webID] = schedule; } } } } catch { } // 釋放 webclient w.Dispose(); } } return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByBkBF(int allianceID, string gameType, string webCountry, string webAllianceName, bool acH = false) { // 沒有資料就離開 if (!bfLoadComplete || string.IsNullOrEmpty(bfHtml)) return null; Dictionary<string, GameInfo> result = new Dictionary<string, GameInfo>(); GameInfo gameInfo = null; // 判斷資料 string[] all = bfHtml.Split(new string[] { "¬~ZA÷" }, StringSplitOptions.RemoveEmptyEntries); // 聯盟 (第一筆是多餘的) for (int allianceIndex = 1; allianceIndex < all.Length; allianceIndex++) { string countryAndAlliance = all[allianceIndex].Split(new string[] { "¬ZB÷" }, StringSplitOptions.RemoveEmptyEntries)[0]; string country = countryAndAlliance.Split(':')[0].Trim(); string alliance = countryAndAlliance.Split(':')[1].Trim(); if (webCountry != country || webAllianceName != alliance)//按國家、聯盟選擇 { continue; } // 比賽集合 string[] games = ("ZA÷" + all[allianceIndex]).Split(new string[] { "~" }, StringSplitOptions.RemoveEmptyEntries); string allianceName = null; // 聯盟資料 // 比賽資料 for (int gameIndex = 0; gameIndex < games.Length; gameIndex++) { Dictionary<string, string> info = new Dictionary<string, string>(); #region 取出資料 string[] data = games[gameIndex].Split(new string[] { "¬" }, StringSplitOptions.RemoveEmptyEntries); // 資料 foreach (string d in data) { string[] txt = d.Split(new string[] { "÷" }, StringSplitOptions.RemoveEmptyEntries); // 記錄 info[txt[0]] = txt[1]; } #endregion #region 第一筆是聯盟 if (gameIndex == 0) { allianceName = info["ZA"]; continue; } else { // 沒有編號就往下處理 if (!info.ContainsKey("AA")) continue; } #endregion // 沒有隊伍就往下處理 if (!info.ContainsKey("AE") || !info.ContainsKey("AF")) continue; // 時間是 1970 年加上 Ti DateTime gameTime = DateTime.Parse("1970/1/1 00:00:00").AddTicks(long.Parse(info["AD"]) * 10000000); // 轉成台灣時間 UTC+8 gameTime = gameTime.AddHours(8); gameInfo = null; gameInfo = new GameInfo(allianceID, gameType, gameTime, info["AA"]); gameInfo.Away = info["AE"].Replace("GOAL", ""); gameInfo.Home = info["AF"].Replace("GOAL", ""); gameInfo.AcH = acH; result[gameInfo.WebID] = gameInfo; } } // 傳回 return result; }
private Dictionary<string, GameInfo> GetSchedulesByNBA(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webNBA.Document == null || this.webNBA.Document.Body == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; #region 取得日期(新版) HtmlElement spanDate = this.webNBA.Document.GetElementById("sbpDate"); if (spanDate.InnerText == null || !DateTime.TryParse(spanDate.InnerText.Replace("Scores for", "").Trim(), out gameDate)) { return null; } #endregion 取得日期 #region 处理数据(新版) string webId = String.Empty; foreach (HtmlElement game in this.webNBA.Document.GetElementsByTagName("article")) { if (game.Id != null && game.GetAttribute("className").ToLower().IndexOf("js-show") != -1) { //网页ID webId = game.Id.Trim(); HtmlElementCollection timeSpan = game.GetElementsByTagName("span"); //开赛时间 if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + timeSpan[0].InnerText.ToUpper().Replace("AM", "").Replace("PM", "").Replace("ET", "").Replace("CT", ""), out gameTime)) continue; //页面的时间,时间+24小时,如4月1日ESPN的赛事必然为隔日4月2号的赛程 //不判定AM PM字样 4/2 gameTime = gameTime.AddHours(12); // 队伍 HtmlElementCollection teams = game.GetElementsByTagName("tbody"); if (teams == null || teams.Count == 0 || teams[0].Id != "teams") { continue; } GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; schedule.Away = teams[0].GetElementsByTagName("h2")[0].InnerText.Trim(); schedule.Home = teams[0].GetElementsByTagName("h2")[1].InnerText.Trim(); // 加入比賽資料 schedules[schedule.WebID] = schedule; } } #endregion 处理数据(新版) #region 取得日期 //foreach (HtmlElement div in this.webNBA.Document.GetElementsByTagName("div")) //{ // if (div.GetAttribute("className") == "key-dates key-dates_sc") // { // // 轉成日期失敗就往下處理 // if (!DateTime.TryParse(div.GetElementsByTagName("h2")[0].InnerText.Replace("Scores for", "").Trim(), out gameDate)) // { // return null; // } // } //} #endregion 取得日期 #region 处理数据 // 處理資料 //foreach (HtmlElement game in this.webNBA.Document.GetElementsByTagName("div")) //{ // if (game.Id != null && game.Id.IndexOf("-gamebox") != -1) // { // string webId = game.Id.Replace("-gamebox", ""); // // 時間錯誤就往下處理 // if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + this.webNBA.Document.GetElementById(webId + "-statusLine1").InnerText.Replace("ET", ""), out gameTime)) // continue; // GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); // schedule.AcH = acH; // // 設定 // schedule.Away = this.webNBA.Document.GetElementById(webId + "-aNameOffset").InnerText; // schedule.Home = this.webNBA.Document.GetElementById(webId + "-hNameOffset").InnerText; // // 加入比賽資料 // schedules[schedule.WebID] = schedule; // } //} #endregion 处理数据 // 傳回 return schedules; }
/// <summary> /// 取得奧訊賽程 /// </summary> /// <param name="allianceID"></param> /// <param name="gameType"></param> /// <param name="lsID"></param> /// /// <param name="acH"></param> /// <returns></returns> private Dictionary<string, GameInfo> GetSchedulesByBet007(int allianceID, string gameType, string lsID, bool acH = false) { DateTime sDate = txtBet007SDate.Value; DateTime eDate = txtBet007EDate.Value; DateTime currentDate = sDate; WebClient client = new WebClient(); client.Encoding = Encoding.GetEncoding("gb2312"); string result = string.Empty; string sourceId = GetGameUseSourceID(allianceID, gameType); Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); // 尋覽指定日期區間取得資料 while (currentDate.Date.CompareTo(eDate.Date) <= 0) { // 下載資料 try { result = client.DownloadString(new Uri(string.Format(@"http://dxbf.bet007.com/nba_date.aspx?time={0}", currentDate.ToString("yyyy-MM-dd")))); } catch { result = client.DownloadString(new Uri(string.Format(@"http://dxbf.titan007.com/nba_date.aspx?time={0}", currentDate.ToString("yyyy-MM-dd")))); } if (!string.IsNullOrEmpty(result)) { // 處理 XML XmlAdapter xmlAdapter = new XmlAdapter(result, false); xmlAdapter.GoToNode("c", "m"); // 取得所有比賽集合 List<string> gameRecord = xmlAdapter.GetAllSubColumns("h"); if (gameRecord.Count == 0) return null; // 尋覽取回的資料集 foreach (var game in gameRecord) { // 切割資料欄位 string[] gameCell = game.Split('^'); // 判斷聯盟ID是否等於指定的聯盟 if (gameCell[37] == lsID) { GameInfo schedule = null; // 比賽ID string webId = gameCell[0]; // 比賽時間 DateTime gameTime = DateTime.Parse(gameCell[42] + "年" + gameCell[4].Replace("<br>", " ")); schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 主客調換 // 主隊 string homeName = gameCell[8].Split(',')[2]; schedule.Home = homeName.Substring(0, (homeName.IndexOf("[") >= 0) ? homeName.IndexOf("[") : homeName.Length); // 客隊 string awayName = gameCell[10].Split(',')[2]; schedule.Away = awayName.Substring(0, (awayName.IndexOf("[") >= 0) ? awayName.IndexOf("[") : awayName.Length); // 指定來源 schedule.SourceID = sourceId; // 加入賽事 schedules[schedule.WebID] = schedule; } else continue; } } currentDate = currentDate.AddDays(1); } return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByKHL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webKHL.Document == null || this.webKHL.Document.Body == null || this.webKHL.Document.GetElementById("content") == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); string gameDateStr = null; DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; // 處理資料 foreach (HtmlElement div in this.webKHL.Document.GetElementById("content").Children) { // 判斷日期 if (div.GetAttribute("className") == "matchDate") { gameDateStr = div.InnerText; if (gameDateStr.IndexOf("(") != -1) gameDateStr = gameDateStr.Substring(0, gameDateStr.IndexOf("(")).Trim(); // 轉換日期失敗就往下處理 if (!DateTime.TryParse(gameDateStr, out gameDate)) { gameDateStr = null; continue; } } // 判斷比賽 if (div.GetAttribute("className") == "matches" && !string.IsNullOrEmpty(gameDateStr)) { foreach (HtmlElement game in div.GetElementsByTagName("div")) { if (game.GetAttribute("className") == "match") { string webId = game.GetElementsByTagName("div")[1].InnerText; string gameTimeStr = game.GetElementsByTagName("div")[2].InnerHtml.Replace("<!--", "").Replace("-->", "").Trim(); if (gameTimeStr.IndexOf(" ") != -1) gameTimeStr = gameTimeStr.Substring(0, gameTimeStr.IndexOf(" ")).Trim(); // 轉換日期失敗就往下處理 if (!DateTime.TryParse(gameDate.ToString("yyyy/MM/dd") + " " + gameTimeStr, out gameTime)) continue; GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = game.GetElementsByTagName("table")[0].GetElementsByTagName("tr")[0].GetElementsByTagName("td")[0].InnerText; schedule.Home = game.GetElementsByTagName("table")[0].GetElementsByTagName("tr")[1].GetElementsByTagName("td")[0].InnerText; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } } //string webId = null; //string txt = game.GetElementsByTagName("h4")[0].InnerText; //// 判斷時間 //if (txt.LastIndexOf(" ") != -1) // txt = txt.Substring(0, txt.LastIndexOf(" ")).Trim(); //// 時間錯誤就往下處理 //if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + this.webNBA.Document.GetElementById(webId + "-statusLine1").InnerText.Replace("ET", ""), out gameTime)) continue; //GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); //schedule.AcH = acH; //// 設定 //schedule.Away = this.webNBA.Document.GetElementById(webId + "-aNameOffset").InnerText; //schedule.Home = this.webNBA.Document.GetElementById(webId + "-hNameOffset").InnerText; //// 判斷隊名 //if (teamName != null) //{ // if (teamName.ContainsKey(schedule.Away)) schedule.Away = teamName[schedule.Away]; // if (teamName.ContainsKey(schedule.Home)) schedule.Home = teamName[schedule.Home]; //} //// 加入比賽資料 //schedules[schedules.Count.ToString()] = schedule; } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByAsiascore(int allianceID, string gameType, string nation, string category, bool acH = false) { // 沒有資料就離開 if (this.webAsiascore.Document == null || this.webAsiascore.Document.Body == null || this.webAsiascore.Document.GetElementById("preload") == null || this.webAsiascore.Document.GetElementById("preload").Style == null || this.webAsiascore.Document.GetElementById("preload").Style.IndexOf("none") == -1) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); Dictionary<string, string> TeamInfo = new Dictionary<string, string>(); HtmlElement dataDoc = this.webAsiascore.Document.GetElementById("fsbody"); // fs // 判斷資料 if (dataDoc != null) { // 取得來源ID string sourceId = GetGameUseSourceID(allianceID, gameType); string[] UfcGameDate = null; foreach (HtmlElement span in dataDoc.GetElementsByTagName("span")) { if (span.GetAttribute("classname") == "day today")//取得開賽日期 { UfcGameDate = span.InnerText.Split(new char[] { ' ' })[0].Split(new char[] { '/' });// 22/02 break; } } // 資料 foreach (HtmlElement table in dataDoc.GetElementsByTagName("table")) { HtmlElementCollection trDoc = table.GetElementsByTagName("tr"); // 判斷資料 if (trDoc.Count <= 1) continue; HtmlElementCollection tdDoc = trDoc[0].GetElementsByTagName("td"); // 判斷資料 if (tdDoc.Count != 2) continue; string gameNation = tdDoc[1].InnerText.ToLower().Trim(); GameInfo schedule = null; // 判斷資料 if (gameNation.IndexOf(nation) == -1 || gameNation.IndexOf(category) == -1) continue; for (int i = 1; i < trDoc.Count; i++) { // 沒有編號就往下處理 if (trDoc[i].Id == null) continue; HtmlElement tr = trDoc[i]; string webId = tr.Id.Substring(tr.Id.LastIndexOf("_") + 1); DateTime gameTime = DateTime.Now; tdDoc = tr.GetElementsByTagName("td"); // 客隊 if (tdDoc.Count == 12 || (gameType.ToLower() == "ufc" && tdDoc.Count == 7))//格鬥賽 { #region 比賽時間 if (tdDoc[1].InnerText == null) continue; // 取得字串 string gameTimeStr = tdDoc[1].InnerText.Replace("\r\n", " "); // 錯誤處理 try { if (gameType.ToLower() == "ufc" && UfcGameDate != null)//格鬥賽 { //比賽時間 gameTimeStr = string.Format("{0}/{1}/{2} {3}", gameTime.ToString("yyyy"), UfcGameDate[1], UfcGameDate[0], gameTimeStr); string[] magnitude = {"FLYWEIGHT", "BANTAMWEIGHT", "FEATHERWEIGHT", "LIGHTWEIGHT", "WELTERWEIGHT", "MIDDLEWEIGHT", "LIGHT HEAVYWEIGHT", "HEAVYWEIGHT"}; foreach (HtmlElement span in table.GetElementsByTagName("span")) { if (span.GetAttribute("classname") == "country_part")//取得量級 { string w = span.InnerText.Replace(":", "").Trim(); for (int index = 0; index < magnitude.Length; index++) { if (w == magnitude[index]) { allianceID = index + 2; //[dbo].[UFCAlliance] 區別量級 break; } } } } } else { // 判斷日期並格式化日期 if (gameTimeStr.Length > 5) { gameTimeStr = gameTime.ToString("yyyy") + "/" + gameTimeStr.Substring(3, 2) + "/" + gameTimeStr.Substring(0, 2) + " " + gameTimeStr.Substring(7); } else { gameTimeStr = gameTime.ToString("yyyy/MM/dd") + " " + gameTimeStr.Substring(0, 2) + ":" + gameTimeStr.Substring(3, 2); } } // 轉成日期 if (!DateTime.TryParse(gameTimeStr, out gameTime)) continue; //新年1月分 跨年问题 if (gameTime.Month == 1 && DateTime.Now.Month == 12) { gameTime = gameTime.AddYears(1); } } catch { continue; } // 錯誤就往下處理 // 开赛时间小于当前时间 就不于显示 添加 if (gameTime < DateTime.Now) { continue; } #endregion 比賽時間 schedule = null; schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = tdDoc[3].InnerText.Trim(); } // 主隊 if ((tdDoc.Count == 7 && gameType.ToLower().IndexOf("ufc") == -1) || (tdDoc.Count == 1 && gameType.ToLower().IndexOf("ufc") > -1))//格鬥賽 { // 資料不正確就往下處理 if (schedule == null || schedule.WebID != webId) continue; // 設定 schedule.Home = tdDoc[0].InnerText.Trim(); // 加入比賽資料 schedule.SourceID = sourceId; if (schedule.GameType.ToLower() == "ufc")//格鬥賽 預設比賽類型 3回合 schedule.GameType += "3"; schedules[schedule.WebID] = schedule; schedule = null; } // 主隊+客隊 (新格式) if (tdDoc.Count == 4 || tdDoc.Count == 6) { #region 比賽時間 if (tdDoc[1].InnerText == null) continue; // 取得字串 string gameTimeStr = tdDoc[1].InnerText.Replace("\r\n", " "); // 錯誤處理 try { // 判斷日期並格式化日期 if (gameTimeStr.Length > 5) { gameTimeStr = gameTime.ToString("yyyy") + "/" + gameTimeStr.Substring(3, 2) + "/" + gameTimeStr.Substring(0, 2) + " " + gameTimeStr.Substring(7); } else { gameTimeStr = gameTime.ToString("yyyy/MM/dd") + " " + gameTimeStr.Substring(0, 2) + ":" + gameTimeStr.Substring(3, 2); } // 轉成日期 if (!DateTime.TryParse(gameTimeStr, out gameTime)) continue; //新年1月分 跨年问题 if (gameTime.Month == 1 && DateTime.Now.Month == 12) { gameTime = gameTime.AddYears(1); } } catch { continue; } // 錯誤就往下處理 // 开赛时间小于当前时间 就不于显示 添加 if (gameTime < DateTime.Now) { continue; } #endregion 比賽時間 schedule = null; schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = tdDoc[2].InnerText.Trim(); schedule.Home = tdDoc[3].InnerText.Trim(); // 加入比賽資料 schedule.SourceID = sourceId; schedules[schedule.WebID] = schedule; schedule = null; } } } } // 傳回 return schedules; }
// 2014/05/21: PL 爆米花夏季聯盟 private Dictionary<string, GameInfo> GetSchedulesByPL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webPL.Document == null || this.webPL.Document.Body == null) return null; HtmlElement divMain = this.webPL.Document.GetElementById("main"); if (divMain == null) { return null; } Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); // 賽局編號(自訂) int gameNum = 0; string gameDateYear = null; string gameDateMonth = null; string webID = null; string sourceId = GetGameUseSourceID(allianceID, gameType); //DateTime gameDate = DateTime.Now; #region 取得年度/月份 foreach (HtmlElement select in divMain.GetElementsByTagName("select")) { string name = select.GetAttribute("name").ToLower(); if (!name.Equals("month") && !name.Equals("year")) { continue; } string value = ""; // 取得值 foreach (HtmlElement option in select.Children) { if (option.GetAttribute("selected").ToLower().Equals("true")) { value = option.GetAttribute("value"); break; } } // 月份 if (name.Equals("month")) { gameDateMonth = value; } // 年度 else if (name.Equals("year")) { gameDateYear = value; } } // 沒有年份/月份就離開 if (String.IsNullOrEmpty(gameDateYear) || String.IsNullOrEmpty(gameDateMonth)) { return null; } #endregion #region 取得資料 foreach (HtmlElement table in divMain.GetElementsByTagName("table")) { var tdColl = (from HtmlElement td in table.GetElementsByTagName("td") let className = td.GetAttribute("className").ToLower() where className.Contains("gridc") select td); if (tdColl.Any()) { foreach (HtmlElement td in tdColl) { HtmlElementCollection spanColl = td.GetElementsByTagName("span"); // 小於 2 表示無賽事 if (spanColl.Count < 1) { continue; } // 日期 string day = spanColl[0].InnerText; // 沒有日期則不處理 if (String.IsNullOrEmpty(day)) { continue; } //隊伍資訊 var teamColl = (from HtmlElement span in spanColl let className = span.GetAttribute("className").ToLower() where className.Contains("fcdark") select span); // 沒有隊伍則不處理 if (!teamColl.Any()) { continue; } foreach (HtmlElement span in teamColl) { // 範例: 崇越隼鷹《天母》合作金庫@12:00 string[] info = span.InnerText.Split(new string[] { "《", "》", "@" }, StringSplitOptions.None); if (info.Length != 4) { continue; } //比賽時間 DateTime gameTime; string dateTime = String.Format("{0}/{1}/{2} {3}", gameDateYear, gameDateMonth, day, info[3]); // 無法解析時間 不處理 if (!DateTime.TryParse(dateTime, out gameTime)) { continue; } GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webID) { Away = info[0], Home = info[2], SourceID = sourceId, AcH = acH }; gameNum++; string key = gameNum.ToString(); schedules[key] = schedule; } } } } #endregion // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByHB(int allianceID, string gameType, bool acH = false) { Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime GameDate = new DateTime(); DateTime startDate = this.dtpHBSDate.Value.Date; DateTime endDate = this.dtpHBEDate.Value.Date; System.Net.WebClient web = new System.Net.WebClient(); web.Encoding = Encoding.UTF8; string s = ""; // 錯誤處理 try { // 下載資料http://www.knbsbstats.nl/2015/HB/scheduleHB.htm string htmlText = web.DownloadString(string.Format("http://www.knbsbstats.nl/{0}/HB/scheduleHB.htm", startDate.ToString("yyyy"))); // 判斷網頁完成 if (!string.IsNullOrEmpty(htmlText)) { HtmlDocument htmlDoc = new HtmlDocument(); //加载资料 htmlDoc.LoadHtml(htmlText); IEnumerable<HtmlNode> tables = htmlDoc.DocumentNode.Descendants("table"); //检查有没有读到资料 if (htmlDoc == null || tables == null || tables.Count() < 2) { return null; } //变量 DateTime date = DateTime.MinValue;//日期 int count = 0; //循环game节点 foreach (HtmlNode node in tables) { HtmlNode td = node.SelectSingleNode(".//tbody[1]/tr[1]/td[1]"); if (td == null) { continue; } if (td.Attributes["class"].Value == "style1") { //区域性名称和标识符。 https://msdn.microsoft.com/zh-cn/library/System.Globalization.CultureInfo%28v=vs.80%29.aspx IFormatProvider culture = new CultureInfo("nl", true); s = td.InnerText.Trim(); date = DateTime.Parse(td.InnerText.Replace(" ", "").Trim(), culture); } if (date != DateTime.MinValue && startDate <= date && endDate >= date && td.Attributes["class"].Value == "bianco_pi") { //真正的比赛数据 if (!DateTime.TryParse(date.ToString("yyyy-MM-dd ") + node.SelectSingleNode(".//tbody[1]/tr[1]/td[2]").InnerText.Trim(), out GameDate)) { continue; } GameDate = GameDate.AddHours(6);//荷兰时间转换为我们的时间 // 建立賽程 GameInfo schedule = new GameInfo(allianceID, gameType, GameDate, GameDate.ToString("yyyyMMdd") + node.SelectSingleNode(".//tbody[1]/tr[1]/td[7]").InnerText.Trim()); //队伍名称 schedule.Home = node.SelectSingleNode(".//tbody[1]/tr[1]/td[4]").InnerText.Replace(" ", "").Replace("&", "&").Replace("ç", "ç").Trim(); schedule.Away = node.SelectSingleNode(".//tbody[1]/tr[1]/td[5]").InnerText.Replace(" ", "").Replace("&", "&").Replace("ç", "ç").Trim(); ; // 加入比賽資料 schedules[schedule.WebID] = schedule; count++; } //如果时间超出设定范围就退出循环 if ((endDate == date && count == 4) || (endDate < date)) { break; } //1天最多只有4场 if (count == 4) { date = DateTime.MinValue; count = 0; continue; } } } } catch (Exception ex) { throw new Exception(ex.Message + "//" + ex.StackTrace + "==" + s); } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByLMP(int allianceID, string gameType, bool acH = false) { Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; string season = ConfigurationManager.AppSettings["season"].ToString(); DateTime startDate =this.dtpLMPSDate.Value.Date; DateTime endDate = this.dtpLMPEDate.Value.Date; while (startDate.CompareTo(endDate) <= 0) { string gameDateStr = startDate.ToString("yyyy-MM-dd"); // 轉成日期 if (DateTime.TryParse(gameDateStr, out gameDate)) { WebClient web = new WebClient(); // 下載資料 string xmlText = web.DownloadString("http://www.milb.com/lookup/xml/named.schedule_vw_complete.bam?game_date='" + gameDate.ToString("yyyy/MM/dd").Replace("-", "/") + "'&season=" + season + "&league_id=132"); // 判斷網頁完成 if (!string.IsNullOrEmpty(xmlText)) { XmlDocument xmlDoc = new XmlDocument(); // 錯誤處理 try { xmlDoc.LoadXml(xmlText); // 判斷資料 if (xmlDoc["schedule_vw_complete"] != null && xmlDoc["schedule_vw_complete"]["queryResults"] != null) { foreach (XmlNode info in xmlDoc["schedule_vw_complete"]["queryResults"].ChildNodes) { // 判斷時間 if (DateTime.TryParse(info.Attributes["game_time_local"].Value, out gameTime)) { // 計算時間 if (info.Attributes["time_zone_local"] != null) { int zone = 0; int.TryParse(info.Attributes["time_zone_local"].Value, out zone); gameTime = gameTime.AddHours(0 - zone + 8); } // 建立賽程 GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, "gid_" + info.Attributes["game_id"].Value.Replace("/", "_").Replace("-", "_")); schedule.AcH = acH; // 設定 schedule.Away = info.Attributes["away_team_short"].Value; schedule.Home = info.Attributes["home_team_short"].Value; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } } } catch { } } startDate = startDate.AddDays(1); } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByNPB(int allianceID, string gameType, bool acH = false) { bool isWarmUp = false; // 沒有資料就離開 if (this.webNPB.Document == null || this.webNPB.Document.Body == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; //判断是否热身赛界面 if (this.webNPB.DocumentTitle == "プロ野球 - オープン戦 - 日程・結果 -スポーツナビ") { isWarmUp = true; } //資料 foreach (HtmlElement table in this.webNPB.Document.GetElementsByTagName("table")) { // 不是資料就往下處理 if (table.GetAttribute("classname").ToLower().IndexOf("yjms") != 0) continue; string gameDateYear = null; #region 取得年份 foreach (HtmlElement div in this.webNPB.Document.GetElementsByTagName("div")) { // 不是資料就往下處理 if (div.GetAttribute("classname").ToLower().IndexOf("npbsubtitle") == -1) continue; if (div.GetElementsByTagName("strong").Count != 2) continue; gameDateYear = div.GetElementsByTagName("strong")[0].InnerText.Replace("年", "").Trim(); break; } // 沒有年份就離開 if (string.IsNullOrEmpty(gameDateYear)) break; #endregion #region 取得資料 //資料 foreach (HtmlElement tr in table.GetElementsByTagName("tr")) { HtmlElementCollection td = tr.GetElementsByTagName("td"); // 不是資料就往下處理 if (td.Count < 6) continue; string webId = null; #region 取得日期 if (tr.GetElementsByTagName("th").Count == 1) { string gameDateStr = tr.GetElementsByTagName("th")[0].InnerText; // 處理資料 if (gameDateStr.IndexOf("(") != -1) { gameDateStr = gameDateStr.Substring(0, gameDateStr.IndexOf("(")).Trim(); gameDateStr = gameDateStr.Replace("月", "/").Replace("日", ""); } // 轉成日期失敗就往下處理 if (!DateTime.TryParse(gameDateYear + "/" + gameDateStr, out gameDate)) continue; } #endregion #region 取得時間 string[] txt = isWarmUp ? tr.NextSibling.GetElementsByTagName("td")[0].InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries) : td[4].InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 轉成時間失敗就往下處理 if (txt.Length == 0 || !DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + txt[0], out gameTime)) continue; #endregion //已经开赛的比赛不建立 if (gameTime < DateTime.Now) { continue; } GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = td[0].InnerText; schedule.Home = td[2].InnerText; // 加入比賽資料 schedules[schedules.Count.ToString()] = schedule; } #endregion 取得資料 } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByABL(int allianceID, string gameType, bool acH = false) { Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; DateTime startDate = this.dtpABLSDate.Value.Date; DateTime endDate = this.dtpABLEDate.Value.Date; while (startDate.CompareTo(endDate) <= 0) { string gameDateStr = startDate.ToString("yyyy-MM-dd"); // 轉成日期 if (DateTime.TryParse(gameDateStr, out gameDate)) { WebClient web = new WebClient(); // 錯誤處理 try { // 下載資料 http://web.theabl.com.au/gdcross/components/game/win/year_2014/month_12/day_20/master_scoreboard.xml string xmlText = web.DownloadString("http://web.theabl.com.au/gdcross/components/game/win/year_" + gameDate.ToString("yyyy") + "/month_" + gameDate.ToString("MM") + "/day_" + gameDate.ToString("dd") + "/master_scoreboard.xml"); // 判斷網頁完成 if (!string.IsNullOrEmpty(xmlText)) { XmlDocument xmlDoc = new XmlDocument(); //加载资料 xmlDoc.LoadXml(xmlText); XmlElement rootElem = xmlDoc.DocumentElement; //获取到ABL联盟的gamelist XmlNodeList personNodes = rootElem.SelectNodes("//game[@league='ABL']"); //检查有没有读到资料 if (personNodes == null && personNodes.Count == 0) { return null; } //循环game节点 foreach (XmlNode node in personNodes) { //node 为game节点 XmlElement game = (XmlElement)node; string webID = game.GetAttribute("id").Trim(); //日期时间处理 string sDateTime = string.Empty; string sZone = game.GetAttribute("time_zone").ToUpper();//时区 string sAmPm = game.GetAttribute("ampm").ToUpper();//上午or下午 string sTime = game.GetAttribute("time");//时间 string sDate = Convert.ToDateTime(game.GetAttribute("original_date")).ToString("yyyy-MM-dd");//只取日期部分 ////转为24小时制 //string time = string.Format("{0} {1} {2}", sDate, sAmPm, sTime); //DateTime.TryParseExact(time, "yyyy-M-d tt h:m", new System.Globalization.CultureInfo("en-US"), System.Globalization.DateTimeStyles.None, out gameTime); gameTime = Convert.ToDateTime(string.Concat(sDate, " ", sTime)); if (sAmPm.ToLower() == "pm") { gameTime = gameTime.AddHours(12); } //转为台湾时间 switch (sZone) { case "AWST": //等于台湾时间不需要转换 break; case "AEST": //UTC+10 转为台湾时间 -2H gameTime = gameTime.AddHours(-2); break; case "ACDT": case "ACT": //UTC+10:30 转为台湾时间 -2.5H gameTime = gameTime.AddHours(-2.5); break; case "AEDT": case "AET": //UTC +11 转为台湾时间 -3H gameTime = gameTime.AddHours(-3); break; default: //列外时区 按照2小时计算 gameTime = gameTime.AddHours(-2); break; } //双重赛事的 第二场时间 暂定为第一场时间+2H int iCount = 1; string[] arrWebId = webID.Trim().Split('-'); int.TryParse(arrWebId[2], out iCount); if (iCount > 1) { string oldWebId = string.Concat(arrWebId[0], "-", arrWebId[1], "-", iCount - 1); if (schedules.ContainsKey(oldWebId)) { gameTime = schedules[oldWebId].GameTime.AddHours(2); } } // 建立賽程 GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webID); //队伍名称 【城市 队名】中间空格 schedule.Home = string.Format("{0} {1}", game.GetAttribute("home_team_city"), game.GetAttribute("home_team_name")); schedule.Away = string.Format("{0} {1}", game.GetAttribute("away_team_city"), game.GetAttribute("away_team_name")); // 加入比賽資料 schedules[schedule.WebID] = schedule; } } } catch (Exception ex) { //如果错误是属于 来源网404 就不报错(来源网的问题不属于程序问题) if (ex.Message.IndexOf("404") == -1) { throw new Exception(ex.Message); } } startDate = startDate.AddDays(1); } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByNFL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webNFL.Document == null || this.webNFL.Document.Body == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; HtmlElementCollection week = this.webNFL.Document.GetElementById("marketing_over_top").NextSibling.GetElementsByTagName("a"); //选择的参数 string w = string.Empty; string sYyyy = string.Empty; foreach (HtmlElement a in week) { if (a.GetAttribute("className").ToLower().Trim()=="optsel") { ///nfl/schedules/regular/2014/week17 string aHref = a.GetAttribute("href"); string temp = aHref.Substring(aHref.LastIndexOf("regular") + 8 ); w = temp.Substring(temp.IndexOf('/') + 1); sYyyy = temp.Substring(0, 4); break; } } // 資料 foreach (HtmlElement table in this.webNFL.Document.GetElementsByTagName("table")) { // 不是資料就往下處理 if (table.GetAttribute("className") != "data") continue; HtmlElementCollection trDoc = table.GetElementsByTagName("tr"); WebBrowser web = new WebBrowser(); // 沒有資料就往下處理 if (trDoc.Count <= 2) continue; foreach (HtmlElement tr in trDoc) { // 沒有資料就往下處理 if (string.IsNullOrEmpty(tr.InnerText)) continue; HtmlElementCollection td = tr.GetElementsByTagName("td"); string webId = null; if (td.Count == 1) { #region 取得星期 if (tr.GetAttribute("className") == "title") { // 開啟比賽編號網站 web.ScriptErrorsSuppressed = true; string url = null; // 判斷 if (this.webNFL.Url.ToString().IndexOf("preseason") != -1) { url = "http://www.cbssports.com/nfl/scoreboard/" + sYyyy + "/preseason/" + w; } else { url = "http://www.cbssports.com/nfl/scoreboard/" + sYyyy + "/" + w; //url = "http://www.cbssports.com/nfl/scoreboard/"; } web.Navigate(url); // 等待完成 DateTime waitTime = DateTime.Now; double spanSeconds = 0; double maxSeconds = 60; // 30 秒 while (web.ReadyState != WebBrowserReadyState.Complete) { TimeSpan spanTime = DateTime.Now.Subtract(waitTime); // 經過秒數 spanSeconds = Math.Abs(spanTime.TotalSeconds); // 超過就離開 if (spanSeconds >= maxSeconds) break; // 避免死當 Application.DoEvents(); } // 判斷網頁完成 if (web.Document == null) break; } #endregion 取得星期 #region 取得日期 if (tr.GetAttribute("className") == "subtitle") { // 轉成日期失敗就往下處理 if (!DateTime.TryParse(tr.InnerText, out gameDate)) { continue; } } #endregion 取得日期 } // 比賽資料 if (tr.GetAttribute("className").IndexOf("row") != -1 && td.Count == 4) { // 轉成時間失敗就往下處理 if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + td[1].InnerText, out gameTime)) continue; string[] team = td[0].InnerText.Split(new string[] { " at " }, StringSplitOptions.RemoveEmptyEntries); // 找到跟盤編號 foreach (HtmlElement span in web.Document.GetElementsByTagName("span")) { // 判斷跟盤 ID if (span.Id != null && span.Id.ToLower().IndexOf("board") != -1) { if (((HtmlElement)span.Children[0]).InnerText.ToLower().IndexOf("final") != -1) { continue; } string id = span.Id.ToLower().Replace("board", "").Replace(" ", ""); HtmlElementCollection spanTr = span.GetElementsByTagName("tr"); // 判斷是否為正確的格式 if (spanTr.Count >= 3) { List<string> TeamName = new List<string>(); for (int i=0; i < spanTr.Count; i++) { HtmlElement elTr = spanTr[i]; if (elTr.GetAttribute("className").IndexOf("teamInfo") != -1) { string name = elTr.GetElementsByTagName("td")[0].InnerText; if (!TeamName.Contains(name)) { TeamName.Add(name); } } } for (int i = 0; i < TeamName.Count; i++) { int findIndex = TeamName[i].IndexOf("("); if (findIndex != -1) TeamName[i] = TeamName[i].Substring(0, findIndex); } if (TeamName[0].Replace(".", "") == team[0].Replace(".", "") && TeamName[1].Replace(".", "") == team[1].Replace(".", "")) { webId = id; break; } // 相同的隊伍 //if (spanTr[1].GetElementsByTagName("td")[0].InnerText.Replace(".", "") == team[0].Replace(".", "") && // spanTr[2].GetElementsByTagName("td")[0].InnerText.Replace(".", "") == team[1].Replace(".", "")) //{ // webId = id; // break; //} } } } // 沒有編號就往下處理 if (string.IsNullOrEmpty(webId)) continue; GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = team[0]; schedule.Home = team[1]; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByWKBL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webWKBL.Document == null || this.webWKBL.Document.Body == null || this.webWKBL.Document.GetElementById("print") == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); string gameDateStr = null; DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; string gameYear = null; // 取得來源ID string sourceId = GetGameUseSourceID(allianceID, gameType); #region 取得年 // 處理資料 //foreach (HtmlElement div in this.webWKBL.Document.GetElementsByTagName("div")) //{ // //if (div.GetAttribute("className") == "game_month" && // // div.GetElementsByTagName("span").Count == 3) // //{ // // gameYear = div.GetElementsByTagName("img")[0].GetAttribute("alt").Replace("년", "").Trim(); // //} // if (div.GetAttribute("className") == "sel_gsch") // { // gameYear = (div.Children[1] as HtmlElement).GetAttribute("alt").Replace("년", ""); //년 = 年 // } //} foreach (HtmlElement div in this.webWKBL.Document.GetElementsByTagName("div")) { if (div.GetAttribute("className") == "ymbox") { gameYear = (div as HtmlElement).GetElementsByTagName("strong")[0].InnerHtml.Replace(".", ""); break; } } if (string.IsNullOrEmpty(gameYear)) return null; DateTime dGameYear; if (!DateTime.TryParse(gameYear, out dGameYear)) dGameYear = DateTime.Now; #endregion 取得年 // 處理資料 //foreach (HtmlElement game in this.webWKBL.Document.GetElementById("print").GetElementsByTagName("table")) //取賽程資料 foreach (HtmlElement game in this.webWKBL.Document.GetElementById("sch").GetElementsByTagName("tr")) { HtmlElementCollection td = game.GetElementsByTagName("td"); string webId = null; //確定是否有WebID的值 //string checkWebId = game.GetElementsByTagName("td")[4].InnerHtml; //if (checkWebId.Contains("onclick")) //{ // //切割取得WebId的字串 // webId = checkWebId.Split('&')[2].Split('=')[1]; //} // 數量不對就往下處理 if (td.Count != 5) continue; gameDateStr = td[0].InnerText; if (gameDateStr.IndexOf("(") != -1) gameDateStr = gameDateStr.Substring(0, gameDateStr.IndexOf("(")).Trim(); gameDateStr = gameDateStr.Replace("월", "/"); //月 gameDateStr = gameDateStr.Replace("일", ""); //日 if (dGameYear == null) gameDateStr = gameYear + "/" + gameDateStr.Replace(" ", ""); else gameDateStr = dGameYear.Year + "/" + gameDateStr.Replace(" ", ""); // 轉換日期 if (DateTime.TryParse(gameDateStr, out gameDate) && DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + td[3].InnerText, out gameTime)) { //尋找隊伍 td = td[1].GetElementsByTagName("dd"); // 判斷隊伍 if (td.Count < 2) continue; GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = td[0].InnerText.Replace("\r\n", "").Trim(); schedule.Home = td[td.Count - 1].InnerText.Replace("\r\n", "").Trim(); // 加入比賽資料 schedule.SourceID = sourceId; schedules[schedules.Count.ToString()] = schedule; } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByKBO(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webKBO.Document == null || this.webKBO.Document.Body == null || this.webKBO.Document.GetElementById("calendarWrap") == null) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); HtmlElement dataDoc = this.webKBO.Document.GetElementById("calendarWrap"); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; string gameDateStr = String.Empty; string gameTimeStr = String.Empty; // 資料 foreach (HtmlElement table in dataDoc.GetElementsByTagName("table")) { foreach (HtmlElement tr in table.GetElementsByTagName("tr")) { HtmlElementCollection td = tr.GetElementsByTagName("td"); GameInfo schedule = null; string webId = null; int index = 0; #region 取得日期 / 時間 HtmlElementCollection spanColl = tr.GetElementsByTagName("span"); foreach (HtmlElement span in spanColl) { // 取得日期 if ("td_date".Equals(span.GetAttribute("className"))) { gameDateStr = span.InnerText; // 處理資料 if (gameDateStr.IndexOf("(") != -1) { gameDateStr = gameDateStr.Substring(0, gameDateStr.IndexOf("(")).Trim(); gameDateStr = gameDateStr.Replace(".", "/"); } } // 取得時間 if ("td_hour".Equals(span.GetAttribute("className"))) { gameTimeStr = span.InnerText; // 取得 WebID Index int i = 0; HtmlElement el = span.Parent; foreach (HtmlElement elTD in td) { if (el == elTD) { index = i; break; } i++; } } } // 轉換日期失敗就離開 if (!DateTime.TryParse(gameDateStr, out gameDate)) { continue; } // 轉成時間失敗就離開 string gameDateTime = String.Format("{0:yyyy/MM/dd} {1}", gameDate, gameTimeStr); if (!DateTime.TryParse(gameDateTime, out gameTime)) { continue; } #endregion #region 跟盤 ID HtmlElementCollection aDoc = td[index + 2].GetElementsByTagName("a"); // 判斷資料 if (aDoc.Count == 0) { continue; } // 取出資料 webId = aDoc[0].GetAttribute("href"); Uri uri = null; HttpRequest req = null; // 錯誤處理 try { uri = new Uri(webId); // 判斷是否有資料 if (uri.Query != null && !string.IsNullOrEmpty(uri.Query)) { req = new HttpRequest("", uri.AbsoluteUri, uri.Query.Substring(1)); // 判斷資料 if (req["gameid"] != null && !string.IsNullOrEmpty(req["gameid"].Trim())) { webId = req["gameid"]; } } } catch { continue; } // 錯誤,往下處理 #endregion schedule = null; schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = td[index + 1].Children[0].InnerText; schedule.Home = td[index + 1].Children[td[index + 1].Children.Count - 1].InnerText; // 加入比賽資料 schedules[schedule.WebID] = schedule; } } // 傳回 return schedules; }
private Dictionary<string, GameInfo> GetSchedulesByKBL(int allianceID, string gameType, bool acH = false) { // 沒有資料就離開 if (this.webKBL.Document == null || this.webKBL.Document.Body == null || this.webKBL.Document.GetElementById("content") == null || this.webKBL.Document.GetElementById("content").GetElementsByTagName("table").Count != 3) return null; Dictionary<string, GameInfo> schedules = new Dictionary<string, GameInfo>(); DateTime gameDate = DateTime.Now; DateTime gameTime = DateTime.Now; // 取得來源ID string sourceId = GetGameUseSourceID(allianceID, gameType); // 處理資料 foreach (HtmlElement game in this.webKBL.Document.GetElementById("content").GetElementsByTagName("table")[2].GetElementsByTagName("tr")) { // 沒有資料就往下處理 if (game.GetElementsByTagName("td").Count != 3 || game.GetElementsByTagName("td")[2].GetElementsByTagName("a").Count == 0) continue; // 取得日期 if (game.GetElementsByTagName("th").Count == 1) { string txt = game.GetElementsByTagName("th")[0].InnerText; // 判斷文字 if (txt.IndexOf("(") != -1) txt = txt.Substring(0, txt.IndexOf("(")).Trim(); txt = txt.Replace("월", "/").Replace("일", "").Trim(); // 轉換日期 if (!DateTime.TryParse(txt, out gameDate)) continue; } if (gameDate.Date < DateTime.Parse("2013-10-17").Date) continue; // 取得時間 if (!DateTime.TryParse(gameDate.ToString("yyyy-MM-dd") + " " + game.GetElementsByTagName("td")[1].InnerText, out gameTime)) continue; string webId = game.GetElementsByTagName("td")[2].GetElementsByTagName("a")[0].GetAttribute("href"); string[] team = game.GetElementsByTagName("td")[0].InnerText.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); // 資料錯誤就往下處理 if (string.IsNullOrEmpty(webId)) continue; if (team.Length < 2) continue; // 錯誤處理 try { Uri url = new Uri(webId); if (url.Query != null && !string.IsNullOrEmpty(url.Query)) { HttpRequest req = new HttpRequest("", url.AbsoluteUri, url.Query.Substring(1)); // 判斷資料 if (!string.IsNullOrEmpty(req["gameid"].Trim())) { webId = req["gameid"].Trim(); GameInfo schedule = new GameInfo(allianceID, gameType, gameTime, webId); schedule.AcH = acH; // 設定 schedule.Away = team[0]; schedule.Home = team[team.Length - 1]; // 加入比賽資料 schedule.SourceID = sourceId; schedules[schedule.WebID] = schedule; } } } catch { } } // 傳回 return schedules; }