XJ_FootballNewsJob.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. using FCS.Common;
  2. using FCS.Crawler.Tools;
  3. using FCS.Interface;
  4. using FCS.Models;
  5. using HtmlAgilityPack;
  6. using Newtonsoft.Json;
  7. using Quartz;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. namespace FCS.Crawler.ZCLotteryNews
  15. {
  16. /// <summary>
  17. /// 西甲新闻
  18. /// </summary>
  19. public class XJ_FootballNewsJob : CommonJob, IJob
  20. {
  21. public XJ_FootballNewsJob()
  22. {
  23. log = new LogHelper();
  24. services = IOC.Resolve<IDTOpenCode>();
  25. }
  26. public void Execute(IJobExecutionContext context)
  27. {
  28. Config = CommonHelper.GetConfigFromDataMap(context.JobDetail.JobDataMap);
  29. GetAll();
  30. }
  31. /// <summary>
  32. /// 执行主站技巧
  33. /// </summary>
  34. public void GetAll()
  35. {
  36. List<string> urls = new List<string> { "http://sports.163.com/xj/" };
  37. foreach (string url in urls)
  38. {
  39. //获取西甲的新闻列表,
  40. List<Base_News> yc_news = GetOpenListFromMainUrl(url);
  41. foreach (var newItem in yc_news)
  42. {
  43. services.AddNews(currentNews, newItem);
  44. }
  45. }
  46. }
  47. /// <summary>
  48. /// 爬取网易的新闻列表
  49. /// </summary>
  50. /// <param name="mainUrl"></param>
  51. /// <returns></returns>
  52. private List<Base_News> GetOpenListFromMainUrl(string mainUrl)
  53. {
  54. var result = new List<Base_News>();
  55. try
  56. {
  57. var url = new Uri(mainUrl);
  58. var htmlResource = NetHelper.GetUrlResponse(mainUrl, Encoding.GetEncoding("gbk"));
  59. if (htmlResource == null) return result;
  60. HtmlDocument doc = new HtmlDocument();
  61. doc.LoadHtml(htmlResource);
  62. //遍历div下的a标签
  63. HtmlNodeCollection nodeList1 = doc.DocumentNode.SelectNodes("//*[@class='topnews']/ul/li/a");
  64. HtmlNodeCollection nodeList2 = doc.DocumentNode.SelectNodes("//*[@class='topnews']/h2/a");
  65. if (nodeList1 == null && nodeList2 == null) return result;
  66. List<string> urls = new List<string>();
  67. //遍历a标签
  68. foreach (HtmlNode node in nodeList1)
  69. {
  70. HtmlAttribute attr = node.Attributes.SingleOrDefault(a => a.Name.Equals("href"));
  71. if (attr != null)
  72. {
  73. string href = attr.Value;
  74. //去重
  75. if (!urls.Contains(href))
  76. {
  77. urls.Add(href);
  78. }
  79. }
  80. }
  81. foreach (HtmlNode node in nodeList2)
  82. {
  83. HtmlAttribute attr = node.Attributes.SingleOrDefault(a => a.Name.Equals("href"));
  84. if (attr != null)
  85. {
  86. string href = attr.Value;
  87. //去重
  88. if (!urls.Contains(href))
  89. {
  90. urls.Add(href);
  91. }
  92. }
  93. }
  94. //爬取新闻主题
  95. foreach (var url1 in urls)
  96. {
  97. var YCNews = GetNewsModel(url1);
  98. if (YCNews.FullHead != null && YCNews.FullHead != "")
  99. {
  100. result.Add(YCNews);
  101. }
  102. }
  103. }
  104. catch (Exception ex)
  105. {
  106. log.Error(GetType(),
  107. string.Format("【{0}】通过主抓取西甲新闻信息时发生错误,错误信息【{1}】", Config.Area + currentNews, ex.Message));
  108. }
  109. return result;
  110. }
  111. /// <summary>
  112. /// 获取新闻的主题内容
  113. /// </summary>
  114. /// <param name="url"></param>
  115. /// <returns></returns>
  116. private Base_News GetNewsModel(string url)
  117. {
  118. Base_News YCNew = new Base_News();
  119. try
  120. {
  121. var htmlResource = NetHelper.GetUrlResponse(url, Encoding.GetEncoding("gb2312"));
  122. if (htmlResource == null) return YCNew;
  123. HtmlDocument doc = new HtmlDocument();
  124. doc.LoadHtml(htmlResource);
  125. var div = doc.DocumentNode.SelectSingleNode("//*[@class='post_content_main']");
  126. if (div == null) return YCNew;
  127. var Title = div.ChildNodes.Where(node => node.Name == "h1").ToList();
  128. var divContent = doc.DocumentNode.SelectSingleNode("//*[@class='post_text']");
  129. if (divContent == null) return YCNew;
  130. string NewContent = divContent.InnerHtml.Trim();
  131. if (NewContent == "")
  132. {
  133. NewContent = null;
  134. }
  135. var timeDiv = doc.DocumentNode.SelectSingleNode("//*[@class='post_time_source']");
  136. YCNew.ReleaseTime = timeDiv.FirstChild.InnerText.Replace("来源:", "").Replace("网易体育", "").Replace("\n", "");
  137. HtmlDocument imgdoc = new HtmlDocument();
  138. imgdoc.LoadHtml(NewContent);
  139. var img = imgdoc.DocumentNode.SelectSingleNode("//*[@class='f_center']/img");
  140. if (img != null)
  141. {
  142. var imgsrc = img.Attributes.SingleOrDefault(a => a.Name.Equals("src"));
  143. YCNew.SourceAddress = imgsrc.Value;
  144. }
  145. YCNew.Id = Guid.NewGuid().ToString();
  146. YCNew.FullHead = Title[0].InnerText.Trim();
  147. YCNew.AuthorName = "zc55128";
  148. YCNew.NewsContent = NoHTML(NewContent);
  149. YCNew.SourceName = "网易体育 西甲";
  150. YCNew.TypeId = (int)NewsTypeEnum.西甲;
  151. var sql = string.Format(GetLotterySqlByTableName, "Base_DataItemDetail", currentNews.GetEnumDescription());
  152. var res = SqlHelper.ExecuteDataset(CommandType.Text, sql);
  153. if (res != null && res.Tables.Count > 0 && res.Tables[0].Rows.Count > 0)
  154. {
  155. YCNew.CategoryId = res.Tables[0].Rows[0]["Id"].ToString();
  156. }
  157. YCNew.Category = currentNews.GetEnumDescription();
  158. YCNew.CreateDate = DateTime.Now;
  159. }
  160. catch (Exception ex)
  161. {
  162. log.Error(GetType(),
  163. string.Format("【{0}】通过主抓取西甲新闻时发生错误,错误信息【{1}】", Config.Area + currentNews, ex.Message));
  164. }
  165. return YCNew;
  166. }
  167. /// <summary>
  168. /// 组装主站爬取地址
  169. /// </summary>
  170. /// <param name="config"></param>
  171. /// <returns></returns>
  172. private List<string> GetMainUrl(FCSConfig config)
  173. {
  174. List<string> urlList = new List<string>();
  175. string url = config.MainUrl;
  176. int pages = config.MainUrlPages > 0 ? config.MainUrlPages : 1;
  177. for (int i = 1; i <= pages; i++)
  178. {
  179. string res;
  180. if (i == 1)
  181. {
  182. res = "http://sports.163.com/xj/";
  183. }
  184. else
  185. {
  186. res = string.Format(url, i);
  187. }
  188. if (!urlList.Contains(res))
  189. {
  190. urlList.Add(res);
  191. }
  192. }
  193. return urlList;
  194. }
  195. public static string NoHTML(string html) //去除HTML标记
  196. {
  197. Regex regex1 =
  198. new Regex(@"<script[sS]+</script *>",
  199. RegexOptions.IgnoreCase);
  200. Regex regex2 =
  201. new Regex(@" href *= *[sS]*script *:",
  202. RegexOptions.IgnoreCase);
  203. Regex regex3 =
  204. new Regex(@" no[sS]*=",
  205. RegexOptions.IgnoreCase);
  206. Regex regex4 =
  207. new Regex(@"<iframe[sS]+</iframe *>",
  208. RegexOptions.IgnoreCase);
  209. Regex regex5 =
  210. new Regex(@"<frameset[sS]+</frameset *>",
  211. RegexOptions.IgnoreCase);
  212. Regex regex6 =
  213. new Regex(@"<img[^>]+>",
  214. RegexOptions.IgnoreCase);
  215. //Regex regex7 =
  216. // new Regex(@"</p>",
  217. // RegexOptions.IgnoreCase);
  218. //Regex regex8 =
  219. // new Regex(@"<p>",
  220. //RegexOptions.IgnoreCase);
  221. Regex regex9 =
  222. new Regex(@"<[^>]*>",
  223. RegexOptions.IgnoreCase);
  224. html = regex1.Replace(html, ""); //过滤<script></script>标记
  225. html = regex2.Replace(html, ""); //过滤href=javascript: (<A>) 属性
  226. html = regex3.Replace(html, " _disibledevent="); //过滤其它控件的on...事件
  227. html = regex4.Replace(html, ""); //过滤iframe
  228. html = regex5.Replace(html, ""); //过滤frameset
  229. html = regex6.Replace(html, ""); //过滤frameset
  230. html = regex9.Replace(html, "");
  231. html = Regex.Replace(html, "[\f\n\r\t\v]", ""); //过滤回车换行制表符
  232. int index = html.IndexOf("本文来源");//删除文本来源及责任编辑
  233. if (index != -1)
  234. {
  235. html = html.Substring(0, index - 1);
  236. }
  237. html = html.Replace("网易体育", "彩吧足球");
  238. return html;
  239. }
  240. #region 初始化信息
  241. /// <summary>
  242. /// 枚举类型
  243. /// </summary>
  244. private NewsTypeEnum currentNews => NewsTypeEnum.西甲;
  245. #endregion 初始化信息
  246. #region SQL语句
  247. /// <summary>
  248. ///查询类别对应的id
  249. /// </summary>
  250. private static string GetLotterySqlByTableName = @"SELECT TOP 1 [ID],[ItemId],[ItemName] FROM [dbo].[{0}] where ItemCode='NewsCategory' and [ItemName]='{1}' ";//WHERE [IsChecked] = 1 AND [IsPassed] = 1
  251. #endregion
  252. }
  253. }