GrabTheLatestAwardManager.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text;
  5. using HtmlAgilityPack;
  6. using Lottomat.Application.Code;
  7. using Lottomat.Util;
  8. using Lottomat.Utils;
  9. using Lottomat.Utils.HttpHelper;
  10. namespace Lottomat.Application.SystemAutoJob
  11. {
  12. /// <summary>
  13. /// 抓取指定彩种最新期号
  14. /// </summary>
  15. public class GrabTheLatestAwardManager
  16. {
  17. private static HttpHelper helper = new HttpHelper();
  18. /// <summary>
  19. /// 缓存
  20. /// </summary>
  21. private static Dictionary<string, string[]> cacheDictionary = new Dictionary<string, string[]>();
  22. /// <summary>
  23. /// 获取最新期数
  24. /// </summary>
  25. /// <param name="scc"></param>
  26. /// <returns></returns>
  27. public static string GetTheLatestAward(SCCLottery scc)
  28. {
  29. string res = String.Empty;
  30. //读取配置
  31. string[] urlAndXPath = GetRequestUrlAndXPath(scc);
  32. if (!string.IsNullOrEmpty(urlAndXPath[0]) && !string.IsNullOrEmpty(urlAndXPath[1]))
  33. {
  34. //组装参数
  35. HttpItem item = new HttpItem
  36. {
  37. Url = urlAndXPath[0],
  38. Method = "GET",
  39. ContentType = "text/html",
  40. Timeout = 90 * 1000,
  41. ReadWriteTimeout = 90 * 1000,
  42. Encoding = Encoding.UTF8
  43. };
  44. //开始请求
  45. HttpResult result = helper.GetHtml(item);
  46. if (result.StatusCode == HttpStatusCode.OK)
  47. {
  48. string html = result.Html;
  49. if (!string.IsNullOrEmpty(html))
  50. {
  51. HtmlDocument doc = new HtmlDocument();
  52. doc.LoadHtml(html);
  53. HtmlNode node = doc.DocumentNode.SelectSingleNode(urlAndXPath[1]);
  54. //获取最终想要的数据
  55. string text = string.IsNullOrEmpty(node.InnerText) ? node.InnerHtml.ReplaceHtmlTag() : node.InnerText;
  56. //只获取数字部分
  57. List<string> temp = text.GetValueByRegex("-?[1-9]\\d*");
  58. res = temp.Count > 0 ? temp[0] : "";
  59. }
  60. }
  61. }
  62. return res;
  63. }
  64. /// <summary>
  65. /// 获取抓取地址以及XPath
  66. /// </summary>
  67. /// <param name="scc"></param>
  68. /// <returns></returns>
  69. public static string[] GetRequestUrlAndXPath(SCCLottery scc)
  70. {
  71. if (!cacheDictionary.ContainsKey(scc.ToString()))
  72. {
  73. cacheDictionary.Add(scc.ToString(), new[] { ConfigHelper.GetValue("__" + scc.ToString() + "__URL__"), ConfigHelper.GetValue("__" + scc.ToString() + "__XPATH__") });
  74. }
  75. else
  76. {
  77. cacheDictionary[scc.ToString()] = new[]
  78. {
  79. ConfigHelper.GetValue("__" + scc.ToString() + "__URL__"),
  80. ConfigHelper.GetValue("__" + scc.ToString() + "__XPATH__")
  81. };
  82. }
  83. return cacheDictionary[scc.ToString()];
  84. }
  85. }
  86. }