DJ_FootBallNewsJob.cs 9.5 KB

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