main.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  1. # coding=utf-8
  2. import json
  3. import time
  4. import random
  5. from datetime import datetime
  6. import webbrowser
  7. from typing import Dict, List, Tuple, Optional, Union
  8. from pathlib import Path
  9. import os
  10. import requests
  11. import pytz
  12. CONFIG = {
  13. "FEISHU_SEPARATOR": "━━━━━━━━━━━━━━━━━━━", # 飞书消息分割线,注意,其它类型的分割线可能会被飞书过滤而不显示
  14. "REQUEST_INTERVAL": 1000, # 请求间隔(毫秒)
  15. "FEISHU_REPORT_TYPE": "daily", # 飞书报告类型: "current"|"daily"|"both"
  16. "RANK_THRESHOLD": 5, # 排名高亮阈值
  17. "USE_PROXY": True, # 是否启用代理
  18. "DEFAULT_PROXY": "http://127.0.0.1:10086",
  19. "CONTINUE_WITHOUT_FEISHU": True, # 控制在没有飞书 webhook URL 时是否继续执行爬虫, 如果 True ,会依然进行爬虫行为,并在 github 上持续的生成爬取的新闻数据
  20. "FEISHU_WEBHOOK_URL": "", # 飞书机器人的 webhook URL,大概长这样:https://www.feishu.cn/flow/api/trigger-webhook/xxxx, 默认为空,推荐通过GitHub Secrets设置
  21. }
  22. class TimeHelper:
  23. """时间处理工具"""
  24. @staticmethod
  25. def get_beijing_time() -> datetime:
  26. return datetime.now(pytz.timezone("Asia/Shanghai"))
  27. @staticmethod
  28. def format_date_folder() -> str:
  29. return TimeHelper.get_beijing_time().strftime("%Y年%m月%d日")
  30. @staticmethod
  31. def format_time_filename() -> str:
  32. return TimeHelper.get_beijing_time().strftime("%H时%M分")
  33. class FileHelper:
  34. """文件操作工具"""
  35. @staticmethod
  36. def ensure_directory_exists(directory: str) -> None:
  37. Path(directory).mkdir(parents=True, exist_ok=True)
  38. @staticmethod
  39. def get_output_path(subfolder: str, filename: str) -> str:
  40. date_folder = TimeHelper.format_date_folder()
  41. output_dir = Path("output") / date_folder / subfolder
  42. FileHelper.ensure_directory_exists(str(output_dir))
  43. return str(output_dir / filename)
  44. class DataFetcher:
  45. """数据获取器"""
  46. def __init__(self, proxy_url: Optional[str] = None):
  47. self.proxy_url = proxy_url
  48. def fetch_data(
  49. self,
  50. id_info: Union[str, Tuple[str, str]],
  51. max_retries: int = 2,
  52. min_retry_wait: int = 3,
  53. max_retry_wait: int = 5,
  54. ) -> Tuple[Optional[str], str, str]:
  55. """获取指定ID数据,支持重试"""
  56. if isinstance(id_info, tuple):
  57. id_value, alias = id_info
  58. else:
  59. id_value = id_info
  60. alias = id_value
  61. url = f"https://newsnow.busiyi.world/api/s?id={id_value}&latest"
  62. proxies = None
  63. if self.proxy_url:
  64. proxies = {"http": self.proxy_url, "https": self.proxy_url}
  65. headers = {
  66. "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
  67. "Accept": "application/json, text/plain, */*",
  68. "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
  69. "Connection": "keep-alive",
  70. "Cache-Control": "no-cache",
  71. }
  72. retries = 0
  73. while retries <= max_retries:
  74. try:
  75. response = requests.get(
  76. url, proxies=proxies, headers=headers, timeout=10
  77. )
  78. response.raise_for_status()
  79. data_text = response.text
  80. data_json = json.loads(data_text)
  81. status = data_json.get("status", "未知")
  82. if status not in ["success", "cache"]:
  83. raise ValueError(f"响应状态异常: {status}")
  84. status_info = "最新数据" if status == "success" else "缓存数据"
  85. print(f"获取 {id_value} 成功({status_info})")
  86. return data_text, id_value, alias
  87. except Exception as e:
  88. retries += 1
  89. if retries <= max_retries:
  90. base_wait = random.uniform(min_retry_wait, max_retry_wait)
  91. additional_wait = (retries - 1) * random.uniform(1, 2)
  92. wait_time = base_wait + additional_wait
  93. print(f"请求 {id_value} 失败: {e}. {wait_time:.2f}秒后重试...")
  94. time.sleep(wait_time)
  95. else:
  96. print(f"请求 {id_value} 失败: {e}")
  97. return None, id_value, alias
  98. return None, id_value, alias
  99. def crawl_websites(
  100. self,
  101. ids_list: List[Union[str, Tuple[str, str]]],
  102. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  103. ) -> Tuple[Dict, Dict, List]:
  104. """爬取多个网站数据"""
  105. results = {}
  106. id_to_alias = {}
  107. failed_ids = []
  108. for i, id_info in enumerate(ids_list):
  109. if isinstance(id_info, tuple):
  110. id_value, alias = id_info
  111. else:
  112. id_value = id_info
  113. alias = id_value
  114. id_to_alias[id_value] = alias
  115. response, _, _ = self.fetch_data(id_info)
  116. if response:
  117. try:
  118. data = json.loads(response)
  119. results[id_value] = {}
  120. for index, item in enumerate(data.get("items", []), 1):
  121. title = item["title"]
  122. url = item.get("url", "")
  123. mobile_url = item.get("mobileUrl", "")
  124. if title in results[id_value]:
  125. results[id_value][title]["ranks"].append(index)
  126. else:
  127. results[id_value][title] = {
  128. "ranks": [index],
  129. "url": url,
  130. "mobileUrl": mobile_url,
  131. }
  132. except json.JSONDecodeError:
  133. print(f"解析 {id_value} 响应失败")
  134. failed_ids.append(id_value)
  135. except Exception as e:
  136. print(f"处理 {id_value} 数据出错: {e}")
  137. failed_ids.append(id_value)
  138. else:
  139. failed_ids.append(id_value)
  140. if i < len(ids_list) - 1:
  141. actual_interval = request_interval + random.randint(-10, 20)
  142. actual_interval = max(50, actual_interval)
  143. time.sleep(actual_interval / 1000)
  144. print(f"成功: {list(results.keys())}, 失败: {failed_ids}")
  145. return results, id_to_alias, failed_ids
  146. class DataProcessor:
  147. """数据处理器"""
  148. @staticmethod
  149. def detect_latest_new_titles(id_to_alias: Dict) -> Dict:
  150. """检测当日最新批次的新增标题"""
  151. date_folder = TimeHelper.format_date_folder()
  152. txt_dir = Path("output") / date_folder / "txt"
  153. if not txt_dir.exists():
  154. return {}
  155. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  156. if len(files) < 2:
  157. if len(files) == 1:
  158. return DataProcessor._parse_file_titles(files[0])
  159. return {}
  160. latest_file = files[-1]
  161. latest_titles = DataProcessor._parse_file_titles(latest_file)
  162. # 汇总历史标题
  163. historical_titles = {}
  164. for file_path in files[:-1]:
  165. historical_data = DataProcessor._parse_file_titles(file_path)
  166. for source_name, titles_data in historical_data.items():
  167. if source_name not in historical_titles:
  168. historical_titles[source_name] = set()
  169. for title in titles_data.keys():
  170. historical_titles[source_name].add(title)
  171. # 找出新增标题
  172. new_titles = {}
  173. for source_name, latest_source_titles in latest_titles.items():
  174. historical_set = historical_titles.get(source_name, set())
  175. source_new_titles = {}
  176. for title, title_data in latest_source_titles.items():
  177. if title not in historical_set:
  178. source_new_titles[title] = title_data
  179. if source_new_titles:
  180. source_id = None
  181. for id_val, alias in id_to_alias.items():
  182. if alias == source_name:
  183. source_id = id_val
  184. break
  185. if source_id:
  186. new_titles[source_id] = source_new_titles
  187. return new_titles
  188. @staticmethod
  189. def _parse_file_titles(file_path: Path) -> Dict:
  190. """解析单个txt文件的标题数据"""
  191. titles_by_source = {}
  192. with open(file_path, "r", encoding="utf-8") as f:
  193. content = f.read()
  194. sections = content.split("\n\n")
  195. for section in sections:
  196. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  197. continue
  198. lines = section.strip().split("\n")
  199. if len(lines) < 2:
  200. continue
  201. source_name = lines[0].strip()
  202. titles_by_source[source_name] = {}
  203. for line in lines[1:]:
  204. if line.strip():
  205. try:
  206. title_part = line.strip()
  207. rank = None
  208. # 提取排名
  209. if (
  210. ". " in title_part
  211. and title_part.split(". ")[0].isdigit()
  212. ):
  213. rank_str, title_part = title_part.split(". ", 1)
  214. rank = int(rank_str)
  215. # 提取MOBILE URL
  216. mobile_url = ""
  217. if " [MOBILE:" in title_part:
  218. title_part, mobile_part = title_part.rsplit(
  219. " [MOBILE:", 1
  220. )
  221. if mobile_part.endswith("]"):
  222. mobile_url = mobile_part[:-1]
  223. # 提取URL
  224. url = ""
  225. if " [URL:" in title_part:
  226. title_part, url_part = title_part.rsplit(" [URL:", 1)
  227. if url_part.endswith("]"):
  228. url = url_part[:-1]
  229. title = title_part.strip()
  230. ranks = [rank] if rank is not None else [1]
  231. titles_by_source[source_name][title] = {
  232. "ranks": ranks,
  233. "url": url,
  234. "mobileUrl": mobile_url,
  235. }
  236. except Exception as e:
  237. print(f"解析标题行出错: {line}, 错误: {e}")
  238. return titles_by_source
  239. @staticmethod
  240. def save_titles_to_file(results: Dict, id_to_alias: Dict, failed_ids: List) -> str:
  241. """保存标题到文件"""
  242. file_path = FileHelper.get_output_path(
  243. "txt", f"{TimeHelper.format_time_filename()}.txt"
  244. )
  245. with open(file_path, "w", encoding="utf-8") as f:
  246. for id_value, title_data in results.items():
  247. display_name = id_to_alias.get(id_value, id_value)
  248. f.write(f"{display_name}\n")
  249. # 按排名排序标题
  250. sorted_titles = []
  251. for title, info in title_data.items():
  252. if isinstance(info, dict):
  253. ranks = info.get("ranks", [])
  254. url = info.get("url", "")
  255. mobile_url = info.get("mobileUrl", "")
  256. else:
  257. ranks = info if isinstance(info, list) else []
  258. url = ""
  259. mobile_url = ""
  260. rank = ranks[0] if ranks else 1
  261. sorted_titles.append((rank, title, url, mobile_url))
  262. sorted_titles.sort(key=lambda x: x[0])
  263. for rank, title, url, mobile_url in sorted_titles:
  264. line = f"{rank}. {title}"
  265. if url:
  266. line += f" [URL:{url}]"
  267. if mobile_url:
  268. line += f" [MOBILE:{mobile_url}]"
  269. f.write(line + "\n")
  270. f.write("\n")
  271. if failed_ids:
  272. f.write("==== 以下ID请求失败 ====\n")
  273. for id_value in failed_ids:
  274. display_name = id_to_alias.get(id_value, id_value)
  275. f.write(f"{display_name} (ID: {id_value})\n")
  276. return file_path
  277. @staticmethod
  278. def load_frequency_words(
  279. frequency_file: str = "frequency_words.txt",
  280. ) -> Tuple[List[Dict], List[str]]:
  281. """加载频率词配置"""
  282. frequency_path = Path(frequency_file)
  283. if not frequency_path.exists():
  284. print(f"频率词文件 {frequency_file} 不存在")
  285. return [], []
  286. with open(frequency_path, "r", encoding="utf-8") as f:
  287. content = f.read()
  288. word_groups = [
  289. group.strip() for group in content.split("\n\n") if group.strip()
  290. ]
  291. processed_groups = []
  292. filter_words = []
  293. for group in word_groups:
  294. words = [word.strip() for word in group.split("\n") if word.strip()]
  295. group_required_words = []
  296. group_normal_words = []
  297. group_filter_words = []
  298. for word in words:
  299. if word.startswith("!"):
  300. filter_words.append(word[1:])
  301. group_filter_words.append(word[1:])
  302. elif word.startswith("+"):
  303. group_required_words.append(word[1:])
  304. else:
  305. group_normal_words.append(word)
  306. if group_required_words or group_normal_words:
  307. if group_normal_words:
  308. group_key = " ".join(group_normal_words)
  309. else:
  310. group_key = " ".join(group_required_words)
  311. processed_groups.append(
  312. {
  313. "required": group_required_words,
  314. "normal": group_normal_words,
  315. "group_key": group_key,
  316. }
  317. )
  318. return processed_groups, filter_words
  319. @staticmethod
  320. def read_all_today_titles() -> Tuple[Dict, Dict, Dict]:
  321. """读取当天所有标题文件"""
  322. date_folder = TimeHelper.format_date_folder()
  323. txt_dir = Path("output") / date_folder / "txt"
  324. if not txt_dir.exists():
  325. return {}, {}, {}
  326. all_results = {}
  327. id_to_alias = {}
  328. title_info = {}
  329. files = sorted([f for f in txt_dir.iterdir() if f.suffix == ".txt"])
  330. for file_path in files:
  331. time_info = file_path.stem
  332. with open(file_path, "r", encoding="utf-8") as f:
  333. content = f.read()
  334. sections = content.split("\n\n")
  335. for section in sections:
  336. if not section.strip() or "==== 以下ID请求失败 ====" in section:
  337. continue
  338. lines = section.strip().split("\n")
  339. if len(lines) < 2:
  340. continue
  341. source_name = lines[0].strip()
  342. title_data = {}
  343. for line in lines[1:]:
  344. if line.strip():
  345. try:
  346. rank = None
  347. title_part = line.strip()
  348. # 提取行首的排名数字
  349. if (
  350. ". " in title_part
  351. and title_part.split(". ")[0].isdigit()
  352. ):
  353. parts = title_part.split(". ", 1)
  354. rank = int(parts[0])
  355. title_part = parts[1]
  356. # 提取 MOBILE URL
  357. mobile_url = ""
  358. if " [MOBILE:" in title_part:
  359. title_part, mobile_part = title_part.rsplit(
  360. " [MOBILE:", 1
  361. )
  362. if mobile_part.endswith("]"):
  363. mobile_url = mobile_part[:-1]
  364. # 提取 URL
  365. url = ""
  366. if " [URL:" in title_part:
  367. title_part, url_part = title_part.rsplit(
  368. " [URL:", 1
  369. )
  370. if url_part.endswith("]"):
  371. url = url_part[:-1]
  372. title = title_part.strip()
  373. ranks = [rank] if rank is not None else [1]
  374. title_data[title] = {
  375. "ranks": ranks,
  376. "url": url,
  377. "mobileUrl": mobile_url,
  378. }
  379. except Exception as e:
  380. print(f"解析标题行出错: {line}, 错误: {e}")
  381. DataProcessor._process_source_data(
  382. source_name,
  383. title_data,
  384. time_info,
  385. all_results,
  386. title_info,
  387. id_to_alias,
  388. )
  389. # 转换为ID格式
  390. id_results = {}
  391. id_title_info = {}
  392. for name, titles in all_results.items():
  393. for id_value, alias in id_to_alias.items():
  394. if alias == name:
  395. id_results[id_value] = titles
  396. id_title_info[id_value] = title_info[name]
  397. break
  398. return id_results, id_to_alias, id_title_info
  399. @staticmethod
  400. def _process_source_data(
  401. source_name: str,
  402. title_data: Dict,
  403. time_info: str,
  404. all_results: Dict,
  405. title_info: Dict,
  406. id_to_alias: Dict,
  407. ) -> None:
  408. """处理来源数据,合并重复标题"""
  409. if source_name not in all_results:
  410. all_results[source_name] = title_data
  411. if source_name not in title_info:
  412. title_info[source_name] = {}
  413. for title, data in title_data.items():
  414. ranks = data.get("ranks", [])
  415. url = data.get("url", "")
  416. mobile_url = data.get("mobileUrl", "")
  417. title_info[source_name][title] = {
  418. "first_time": time_info,
  419. "last_time": time_info,
  420. "count": 1,
  421. "ranks": ranks,
  422. "url": url,
  423. "mobileUrl": mobile_url,
  424. }
  425. reversed_id = source_name.lower().replace(" ", "-")
  426. id_to_alias[reversed_id] = source_name
  427. else:
  428. for title, data in title_data.items():
  429. ranks = data.get("ranks", [])
  430. url = data.get("url", "")
  431. mobile_url = data.get("mobileUrl", "")
  432. if title not in all_results[source_name]:
  433. all_results[source_name][title] = {
  434. "ranks": ranks,
  435. "url": url,
  436. "mobileUrl": mobile_url,
  437. }
  438. title_info[source_name][title] = {
  439. "first_time": time_info,
  440. "last_time": time_info,
  441. "count": 1,
  442. "ranks": ranks,
  443. "url": url,
  444. "mobileUrl": mobile_url,
  445. }
  446. else:
  447. existing_data = all_results[source_name][title]
  448. existing_ranks = existing_data.get("ranks", [])
  449. existing_url = existing_data.get("url", "")
  450. existing_mobile_url = existing_data.get("mobileUrl", "")
  451. merged_ranks = existing_ranks.copy()
  452. for rank in ranks:
  453. if rank not in merged_ranks:
  454. merged_ranks.append(rank)
  455. all_results[source_name][title] = {
  456. "ranks": merged_ranks,
  457. "url": existing_url or url,
  458. "mobileUrl": existing_mobile_url or mobile_url,
  459. }
  460. title_info[source_name][title]["last_time"] = time_info
  461. title_info[source_name][title]["ranks"] = merged_ranks
  462. title_info[source_name][title]["count"] += 1
  463. if not title_info[source_name][title].get("url"):
  464. title_info[source_name][title]["url"] = url
  465. if not title_info[source_name][title].get("mobileUrl"):
  466. title_info[source_name][title]["mobileUrl"] = mobile_url
  467. class StatisticsCalculator:
  468. """统计计算器"""
  469. @staticmethod
  470. def _matches_word_groups(
  471. title: str, word_groups: List[Dict], filter_words: List[str]
  472. ) -> bool:
  473. """检查标题是否匹配词组规则"""
  474. title_lower = title.lower()
  475. # 过滤词检查
  476. if any(filter_word.lower() in title_lower for filter_word in filter_words):
  477. return False
  478. # 词组匹配检查
  479. for group in word_groups:
  480. required_words = group["required"]
  481. normal_words = group["normal"]
  482. # 必须词检查
  483. if required_words:
  484. all_required_present = all(
  485. req_word.lower() in title_lower for req_word in required_words
  486. )
  487. if not all_required_present:
  488. continue
  489. # 普通词检查
  490. if normal_words:
  491. any_normal_present = any(
  492. normal_word.lower() in title_lower for normal_word in normal_words
  493. )
  494. if not any_normal_present:
  495. continue
  496. return True
  497. return False
  498. @staticmethod
  499. def count_word_frequency(
  500. results: Dict,
  501. word_groups: List[Dict],
  502. filter_words: List[str],
  503. id_to_alias: Dict,
  504. title_info: Optional[Dict] = None,
  505. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  506. new_titles: Optional[Dict] = None,
  507. ) -> Tuple[List[Dict], int]:
  508. """统计词频,支持必须词、频率词、过滤词,并标记新增标题"""
  509. word_stats = {}
  510. total_titles = 0
  511. processed_titles = {}
  512. if title_info is None:
  513. title_info = {}
  514. if new_titles is None:
  515. new_titles = {}
  516. for group in word_groups:
  517. group_key = group["group_key"]
  518. word_stats[group_key] = {"count": 0, "titles": {}}
  519. for source_id, titles_data in results.items():
  520. total_titles += len(titles_data)
  521. if source_id not in processed_titles:
  522. processed_titles[source_id] = {}
  523. for title, title_data in titles_data.items():
  524. if title in processed_titles.get(source_id, {}):
  525. continue
  526. # 使用统一的匹配逻辑
  527. if not StatisticsCalculator._matches_word_groups(
  528. title, word_groups, filter_words
  529. ):
  530. continue
  531. source_ranks = title_data.get("ranks", [])
  532. source_url = title_data.get("url", "")
  533. source_mobile_url = title_data.get("mobileUrl", "")
  534. # 找到匹配的词组
  535. title_lower = title.lower()
  536. for group in word_groups:
  537. required_words = group["required"]
  538. normal_words = group["normal"]
  539. # 再次检查匹配
  540. if required_words:
  541. all_required_present = all(
  542. req_word.lower() in title_lower
  543. for req_word in required_words
  544. )
  545. if not all_required_present:
  546. continue
  547. if normal_words:
  548. any_normal_present = any(
  549. normal_word.lower() in title_lower
  550. for normal_word in normal_words
  551. )
  552. if not any_normal_present:
  553. continue
  554. group_key = group["group_key"]
  555. word_stats[group_key]["count"] += 1
  556. if source_id not in word_stats[group_key]["titles"]:
  557. word_stats[group_key]["titles"][source_id] = []
  558. first_time = ""
  559. last_time = ""
  560. count_info = 1
  561. ranks = source_ranks if source_ranks else []
  562. url = source_url
  563. mobile_url = source_mobile_url
  564. if (
  565. title_info
  566. and source_id in title_info
  567. and title in title_info[source_id]
  568. ):
  569. info = title_info[source_id][title]
  570. first_time = info.get("first_time", "")
  571. last_time = info.get("last_time", "")
  572. count_info = info.get("count", 1)
  573. if "ranks" in info and info["ranks"]:
  574. ranks = info["ranks"]
  575. url = info.get("url", source_url)
  576. mobile_url = info.get("mobileUrl", source_mobile_url)
  577. if not ranks:
  578. ranks = [99]
  579. time_display = StatisticsCalculator._format_time_display(
  580. first_time, last_time
  581. )
  582. source_alias = id_to_alias.get(source_id, source_id)
  583. is_new = source_id in new_titles and title in new_titles[source_id]
  584. word_stats[group_key]["titles"][source_id].append(
  585. {
  586. "title": title,
  587. "source_alias": source_alias,
  588. "first_time": first_time,
  589. "last_time": last_time,
  590. "time_display": time_display,
  591. "count": count_info,
  592. "ranks": ranks,
  593. "rank_threshold": rank_threshold,
  594. "url": url,
  595. "mobileUrl": mobile_url,
  596. "is_new": is_new,
  597. }
  598. )
  599. if source_id not in processed_titles:
  600. processed_titles[source_id] = {}
  601. processed_titles[source_id][title] = True
  602. break
  603. stats = []
  604. for group_key, data in word_stats.items():
  605. all_titles = []
  606. for source_id, title_list in data["titles"].items():
  607. all_titles.extend(title_list)
  608. stats.append(
  609. {
  610. "word": group_key,
  611. "count": data["count"],
  612. "titles": all_titles,
  613. "percentage": (
  614. round(data["count"] / total_titles * 100, 2)
  615. if total_titles > 0
  616. else 0
  617. ),
  618. }
  619. )
  620. stats.sort(key=lambda x: x["count"], reverse=True)
  621. return stats, total_titles
  622. @staticmethod
  623. def _format_rank_base(
  624. ranks: List[int], rank_threshold: int = 5, format_type: str = "html"
  625. ) -> str:
  626. """基础排名格式化方法"""
  627. if not ranks:
  628. return ""
  629. unique_ranks = sorted(set(ranks))
  630. min_rank = unique_ranks[0]
  631. max_rank = unique_ranks[-1]
  632. # 根据格式类型选择不同的标记方式
  633. if format_type == "html":
  634. highlight_start = "<font color='red'><strong>"
  635. highlight_end = "</strong></font>"
  636. else: # feishu
  637. highlight_start = "<font color='red'>**"
  638. highlight_end = "**</font>"
  639. # 格式化排名显示
  640. if min_rank <= rank_threshold:
  641. if min_rank == max_rank:
  642. return f"{highlight_start}[{min_rank}]{highlight_end}"
  643. else:
  644. return f"{highlight_start}[{min_rank} - {max_rank}]{highlight_end}"
  645. else:
  646. if min_rank == max_rank:
  647. return f"[{min_rank}]"
  648. else:
  649. return f"[{min_rank} - {max_rank}]"
  650. @staticmethod
  651. def _format_rank_for_html(ranks: List[int], rank_threshold: int = 5) -> str:
  652. """格式化HTML排名显示"""
  653. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "html")
  654. @staticmethod
  655. def _format_rank_for_feishu(ranks: List[int], rank_threshold: int = 5) -> str:
  656. """格式化飞书排名显示"""
  657. return StatisticsCalculator._format_rank_base(ranks, rank_threshold, "feishu")
  658. @staticmethod
  659. def _format_time_display(first_time: str, last_time: str) -> str:
  660. """格式化时间显示"""
  661. if not first_time:
  662. return ""
  663. if first_time == last_time or not last_time:
  664. return first_time
  665. else:
  666. return f"[{first_time} ~ {last_time}]"
  667. class ReportGenerator:
  668. """报告生成器"""
  669. @staticmethod
  670. def generate_html_report(
  671. stats: List[Dict],
  672. total_titles: int,
  673. failed_ids: Optional[List] = None,
  674. is_daily: bool = False,
  675. new_titles: Optional[Dict] = None,
  676. id_to_alias: Optional[Dict] = None,
  677. ) -> str:
  678. """生成HTML报告"""
  679. if is_daily:
  680. filename = "当日统计.html"
  681. else:
  682. filename = f"{TimeHelper.format_time_filename()}.html"
  683. file_path = FileHelper.get_output_path("html", filename)
  684. # 数据处理层
  685. report_data = ReportGenerator._prepare_report_data(
  686. stats, failed_ids, new_titles, id_to_alias
  687. )
  688. # 渲染层
  689. html_content = ReportGenerator._render_html_content(
  690. report_data, total_titles, is_daily
  691. )
  692. with open(file_path, "w", encoding="utf-8") as f:
  693. f.write(html_content)
  694. if is_daily:
  695. root_file_path = Path("index.html")
  696. with open(root_file_path, "w", encoding="utf-8") as f:
  697. f.write(html_content)
  698. return file_path
  699. @staticmethod
  700. def _prepare_report_data(
  701. stats: List[Dict],
  702. failed_ids: Optional[List] = None,
  703. new_titles: Optional[Dict] = None,
  704. id_to_alias: Optional[Dict] = None,
  705. ) -> Dict:
  706. """准备报告数据"""
  707. filtered_new_titles = {}
  708. if new_titles and id_to_alias:
  709. word_groups, filter_words = DataProcessor.load_frequency_words()
  710. for source_id, titles_data in new_titles.items():
  711. filtered_titles = ReportGenerator._apply_frequency_filter(
  712. titles_data, word_groups, filter_words
  713. )
  714. if filtered_titles:
  715. filtered_new_titles[source_id] = filtered_titles
  716. processed_stats = []
  717. for stat in stats:
  718. if stat["count"] <= 0:
  719. continue
  720. processed_titles = []
  721. for title_data in stat["titles"]:
  722. processed_title = {
  723. "title": title_data["title"],
  724. "source_alias": title_data["source_alias"],
  725. "time_display": title_data["time_display"],
  726. "count": title_data["count"],
  727. "ranks": title_data["ranks"],
  728. "rank_threshold": title_data["rank_threshold"],
  729. "url": title_data.get("url", ""),
  730. "mobile_url": title_data.get("mobileUrl", ""),
  731. "is_new": title_data.get("is_new", False),
  732. }
  733. processed_titles.append(processed_title)
  734. processed_stats.append(
  735. {
  736. "word": stat["word"],
  737. "count": stat["count"],
  738. "percentage": stat.get("percentage", 0),
  739. "titles": processed_titles,
  740. }
  741. )
  742. processed_new_titles = []
  743. if filtered_new_titles and id_to_alias:
  744. for source_id, titles_data in filtered_new_titles.items():
  745. source_alias = id_to_alias.get(source_id, source_id)
  746. source_titles = []
  747. for title, title_data in titles_data.items():
  748. url, mobile_url, ranks = ReportGenerator._extract_title_data_fields(
  749. title_data
  750. )
  751. processed_title = {
  752. "title": title,
  753. "source_alias": source_alias,
  754. "time_display": "",
  755. "count": 1,
  756. "ranks": ranks,
  757. "rank_threshold": CONFIG["RANK_THRESHOLD"],
  758. "url": url,
  759. "mobile_url": mobile_url,
  760. "is_new": True,
  761. }
  762. source_titles.append(processed_title)
  763. if source_titles:
  764. processed_new_titles.append(
  765. {
  766. "source_id": source_id,
  767. "source_alias": source_alias,
  768. "titles": source_titles,
  769. }
  770. )
  771. return {
  772. "stats": processed_stats,
  773. "new_titles": processed_new_titles,
  774. "failed_ids": failed_ids or [],
  775. "total_new_count": sum(
  776. len(source["titles"]) for source in processed_new_titles
  777. ),
  778. }
  779. @staticmethod
  780. def _extract_title_data_fields(title_data) -> Tuple[str, str, List[int]]:
  781. """提取标题数据的通用字段"""
  782. url = title_data.get("url", "")
  783. mobile_url = title_data.get("mobileUrl", "")
  784. ranks = title_data.get("ranks", [])
  785. return url, mobile_url, ranks
  786. @staticmethod
  787. def _apply_frequency_filter(
  788. titles_data: Dict, word_groups: List[Dict], filter_words: List[str]
  789. ) -> Dict:
  790. """应用频率词过滤逻辑"""
  791. filtered_titles = {}
  792. for title, title_data in titles_data.items():
  793. if StatisticsCalculator._matches_word_groups(
  794. title, word_groups, filter_words
  795. ):
  796. filtered_titles[title] = title_data
  797. return filtered_titles
  798. @staticmethod
  799. def _html_escape(text: str) -> str:
  800. """HTML转义"""
  801. if not isinstance(text, str):
  802. text = str(text)
  803. return (
  804. text.replace("&", "&amp;")
  805. .replace("<", "&lt;")
  806. .replace(">", "&gt;")
  807. .replace('"', "&quot;")
  808. .replace("'", "&#x27;")
  809. )
  810. @staticmethod
  811. def _format_title_html(title_data: Dict) -> str:
  812. """格式化HTML标题显示"""
  813. rank_display = StatisticsCalculator._format_rank_for_html(
  814. title_data["ranks"], title_data["rank_threshold"]
  815. )
  816. link_url = title_data["mobile_url"] or title_data["url"]
  817. escaped_title = ReportGenerator._html_escape(title_data["title"])
  818. escaped_source_alias = ReportGenerator._html_escape(title_data["source_alias"])
  819. if link_url:
  820. escaped_url = ReportGenerator._html_escape(link_url)
  821. formatted_title = f'[{escaped_source_alias}] <a href="{escaped_url}" target="_blank" class="news-link">{escaped_title}</a>'
  822. else:
  823. formatted_title = (
  824. f'[{escaped_source_alias}] <span class="no-link">{escaped_title}</span>'
  825. )
  826. if rank_display:
  827. formatted_title += f" {rank_display}"
  828. if title_data["time_display"]:
  829. escaped_time = ReportGenerator._html_escape(title_data["time_display"])
  830. formatted_title += f" <font color='grey'>- {escaped_time}</font>"
  831. if title_data["count"] > 1:
  832. formatted_title += f" <font color='green'>({title_data['count']}次)</font>"
  833. if title_data["is_new"]:
  834. formatted_title = f"<div class='new-title'>🆕 {formatted_title}</div>"
  835. return formatted_title
  836. @staticmethod
  837. def _render_html_content(
  838. report_data: Dict, total_titles: int, is_daily: bool = False
  839. ) -> str:
  840. """渲染HTML内容"""
  841. html = """
  842. <!DOCTYPE html>
  843. <html>
  844. <head>
  845. <meta charset="UTF-8">
  846. <title>频率词统计报告</title>
  847. <style>
  848. body { font-family: Arial, sans-serif; margin: 20px; }
  849. h1, h2 { color: #333; }
  850. table { border-collapse: collapse; width: 100%; margin-top: 20px; }
  851. th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
  852. th { background-color: #f2f2f2; }
  853. tr:nth-child(even) { background-color: #f9f9f9; }
  854. .word { font-weight: bold; }
  855. .count { text-align: center; }
  856. .percentage { text-align: center; }
  857. .titles { max-width: 500px; }
  858. .source { color: #666; font-style: italic; }
  859. .error { color: #d9534f; }
  860. .news-link {
  861. color: #007bff;
  862. text-decoration: none;
  863. border-bottom: 1px dotted #007bff;
  864. }
  865. .news-link:hover {
  866. color: #0056b3;
  867. text-decoration: underline;
  868. }
  869. .news-link:visited {
  870. color: #6f42c1;
  871. }
  872. .no-link {
  873. color: #333;
  874. }
  875. .new-title {
  876. background-color: #fff3cd;
  877. border: 1px solid #ffc107;
  878. border-radius: 3px;
  879. padding: 2px 6px;
  880. margin: 2px 0;
  881. }
  882. .new-section {
  883. background-color: #d1ecf1;
  884. border: 1px solid #bee5eb;
  885. border-radius: 5px;
  886. padding: 10px;
  887. margin-top: 10px;
  888. }
  889. .new-section h3 {
  890. color: #0c5460;
  891. margin-top: 0;
  892. }
  893. </style>
  894. </head>
  895. <body>
  896. <h1>频率词统计报告</h1>
  897. """
  898. if is_daily:
  899. html += "<p>报告类型: 当日汇总</p>"
  900. now = TimeHelper.get_beijing_time()
  901. html += f"<p>总标题数: {total_titles}</p>"
  902. html += f"<p>生成时间: {now.strftime('%Y-%m-%d %H:%M:%S')}</p>"
  903. # 渲染失败平台
  904. if report_data["failed_ids"]:
  905. html += """
  906. <div class="error">
  907. <h2>请求失败的平台</h2>
  908. <ul>
  909. """
  910. for id_value in report_data["failed_ids"]:
  911. html += f"<li>{ReportGenerator._html_escape(id_value)}</li>"
  912. html += """
  913. </ul>
  914. </div>
  915. """
  916. # 渲染统计表格
  917. html += """
  918. <table>
  919. <tr>
  920. <th>排名</th>
  921. <th>频率词</th>
  922. <th>出现次数</th>
  923. <th>占比</th>
  924. <th>相关标题</th>
  925. </tr>
  926. """
  927. for i, stat in enumerate(report_data["stats"], 1):
  928. formatted_titles = []
  929. for title_data in stat["titles"]:
  930. formatted_title = ReportGenerator._format_title_html(title_data)
  931. formatted_titles.append(formatted_title)
  932. escaped_word = ReportGenerator._html_escape(stat["word"])
  933. html += f"""
  934. <tr>
  935. <td>{i}</td>
  936. <td class="word">{escaped_word}</td>
  937. <td class="count">{stat['count']}</td>
  938. <td class="percentage">{stat.get('percentage', 0)}%</td>
  939. <td class="titles">{"<br>".join(formatted_titles)}</td>
  940. </tr>
  941. """
  942. html += """
  943. </table>
  944. """
  945. # 渲染新增新闻部分
  946. if report_data["new_titles"]:
  947. html += f"""
  948. <div class="new-section">
  949. <h3>🆕 本次新增热点新闻 (共 {report_data['total_new_count']} 条)</h3>
  950. """
  951. for source_data in report_data["new_titles"]:
  952. escaped_source = ReportGenerator._html_escape(
  953. source_data["source_alias"]
  954. )
  955. html += (
  956. f"<h4>{escaped_source} ({len(source_data['titles'])} 条)</h4><ul>"
  957. )
  958. for title_data in source_data["titles"]:
  959. title_data_copy = title_data.copy()
  960. title_data_copy["is_new"] = False
  961. formatted_title = ReportGenerator._format_title_html(
  962. title_data_copy
  963. )
  964. # 移除来源标签
  965. if "] " in formatted_title:
  966. formatted_title = formatted_title.split("] ", 1)[1]
  967. html += f"<li>{formatted_title}</li>"
  968. html += "</ul>"
  969. html += "</div>"
  970. html += """
  971. </body>
  972. </html>
  973. """
  974. return html
  975. @staticmethod
  976. def _format_title_feishu(title_data: Dict, show_source: bool = True) -> str:
  977. """格式化飞书标题显示"""
  978. rank_display = StatisticsCalculator._format_rank_for_feishu(
  979. title_data["ranks"], title_data["rank_threshold"]
  980. )
  981. link_url = title_data["mobile_url"] or title_data["url"]
  982. if link_url:
  983. formatted_title = f"[{title_data['title']}]({link_url})"
  984. else:
  985. formatted_title = title_data["title"]
  986. title_prefix = "🆕 " if title_data["is_new"] else ""
  987. if show_source:
  988. result = f"<font color='grey'>[{title_data['source_alias']}]</font> {title_prefix}{formatted_title}"
  989. else:
  990. result = f"{title_prefix}{formatted_title}"
  991. if rank_display:
  992. result += f" {rank_display}"
  993. if title_data["time_display"]:
  994. result += f" <font color='grey'>- {title_data['time_display']}</font>"
  995. if title_data["count"] > 1:
  996. result += f" <font color='green'>({title_data['count']}次)</font>"
  997. return result
  998. @staticmethod
  999. def _render_feishu_content(report_data: Dict) -> str:
  1000. """渲染飞书内容"""
  1001. text_content = ""
  1002. # 渲染热点词汇统计
  1003. if report_data["stats"]:
  1004. text_content += "📊 **热点词汇统计**\n\n"
  1005. total_count = len(report_data["stats"])
  1006. for i, stat in enumerate(report_data["stats"]):
  1007. word = stat["word"]
  1008. count = stat["count"]
  1009. sequence_display = f"<font color='grey'>[{i + 1}/{total_count}]</font>"
  1010. if count >= 10:
  1011. text_content += f"🔥 {sequence_display} **{word}** : <font color='red'>{count}</font> 条\n\n"
  1012. elif count >= 5:
  1013. text_content += f"📈 {sequence_display} **{word}** : <font color='orange'>{count}</font> 条\n\n"
  1014. else:
  1015. text_content += f"📌 {sequence_display} **{word}** : {count} 条\n\n"
  1016. for j, title_data in enumerate(stat["titles"], 1):
  1017. formatted_title = ReportGenerator._format_title_feishu(
  1018. title_data, show_source=True
  1019. )
  1020. text_content += f" {j}. {formatted_title}\n"
  1021. if j < len(stat["titles"]):
  1022. text_content += "\n"
  1023. if i < len(report_data["stats"]) - 1:
  1024. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1025. if not text_content:
  1026. text_content = "📭 暂无匹配的热点词汇\n\n"
  1027. # 渲染新增新闻部分
  1028. if report_data["new_titles"]:
  1029. if text_content and "暂无匹配" not in text_content:
  1030. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1031. text_content += (
  1032. f"🆕 **本次新增热点新闻** (共 {report_data['total_new_count']} 条)\n\n"
  1033. )
  1034. for source_data in report_data["new_titles"]:
  1035. text_content += f"**{source_data['source_alias']}** ({len(source_data['titles'])} 条):\n"
  1036. for j, title_data in enumerate(source_data["titles"], 1):
  1037. title_data_copy = title_data.copy()
  1038. title_data_copy["is_new"] = False
  1039. formatted_title = ReportGenerator._format_title_feishu(
  1040. title_data_copy, show_source=False
  1041. )
  1042. text_content += f" {j}. {formatted_title}\n"
  1043. text_content += "\n"
  1044. # 渲染失败平台
  1045. if report_data["failed_ids"]:
  1046. if text_content and "暂无匹配" not in text_content:
  1047. text_content += f"\n{CONFIG['FEISHU_SEPARATOR']}\n\n"
  1048. text_content += "⚠️ **数据获取失败的平台:**\n\n"
  1049. for i, id_value in enumerate(report_data["failed_ids"], 1):
  1050. text_content += f" • <font color='red'>{id_value}</font>\n"
  1051. # 添加时间戳
  1052. now = TimeHelper.get_beijing_time()
  1053. text_content += f"\n\n<font color='grey'>更新时间:{now.strftime('%Y-%m-%d %H:%M:%S')}</font>"
  1054. return text_content
  1055. @staticmethod
  1056. def send_to_feishu(
  1057. stats: List[Dict],
  1058. failed_ids: Optional[List] = None,
  1059. report_type: str = "单次爬取",
  1060. new_titles: Optional[Dict] = None,
  1061. id_to_alias: Optional[Dict] = None,
  1062. ) -> bool:
  1063. """发送数据到飞书"""
  1064. webhook_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1065. if not webhook_url:
  1066. print(f"FEISHU_WEBHOOK_URL未设置,跳过飞书通知")
  1067. return False
  1068. headers = {"Content-Type": "application/json"}
  1069. total_titles = sum(len(stat["titles"]) for stat in stats if stat["count"] > 0)
  1070. # 数据处理层
  1071. report_data = ReportGenerator._prepare_report_data(
  1072. stats, failed_ids, new_titles, id_to_alias
  1073. )
  1074. # 渲染层
  1075. text_content = ReportGenerator._render_feishu_content(report_data)
  1076. now = TimeHelper.get_beijing_time()
  1077. payload = {
  1078. "msg_type": "text",
  1079. "content": {
  1080. "total_titles": total_titles,
  1081. "timestamp": now.strftime("%Y-%m-%d %H:%M:%S"),
  1082. "report_type": report_type,
  1083. "text": text_content,
  1084. },
  1085. }
  1086. try:
  1087. response = requests.post(webhook_url, headers=headers, json=payload)
  1088. if response.status_code == 200:
  1089. print(f"飞书通知发送成功 [{report_type}]")
  1090. return True
  1091. else:
  1092. print(
  1093. f"飞书通知发送失败 [{report_type}],状态码:{response.status_code}"
  1094. )
  1095. return False
  1096. except Exception as e:
  1097. print(f"飞书通知发送出错 [{report_type}]:{e}")
  1098. return False
  1099. class NewsAnalyzer:
  1100. """新闻分析器"""
  1101. def __init__(
  1102. self,
  1103. request_interval: int = CONFIG["REQUEST_INTERVAL"],
  1104. feishu_report_type: str = CONFIG["FEISHU_REPORT_TYPE"],
  1105. rank_threshold: int = CONFIG["RANK_THRESHOLD"],
  1106. ):
  1107. self.request_interval = request_interval
  1108. self.feishu_report_type = feishu_report_type
  1109. self.rank_threshold = rank_threshold
  1110. self.is_github_actions = os.environ.get("GITHUB_ACTIONS") == "true"
  1111. self.proxy_url = None
  1112. if not self.is_github_actions and CONFIG["USE_PROXY"]:
  1113. self.proxy_url = CONFIG["DEFAULT_PROXY"]
  1114. print("本地环境,使用代理")
  1115. elif not self.is_github_actions and not CONFIG["USE_PROXY"]:
  1116. print("本地环境,未启用代理")
  1117. else:
  1118. print("GitHub Actions环境,不使用代理")
  1119. self.data_fetcher = DataFetcher(self.proxy_url)
  1120. def generate_daily_summary(self) -> Optional[str]:
  1121. """生成当日统计报告"""
  1122. print("生成当日统计报告...")
  1123. all_results, id_to_alias, title_info = DataProcessor.read_all_today_titles()
  1124. if not all_results:
  1125. print("没有找到当天的数据")
  1126. return None
  1127. total_titles = sum(len(titles) for titles in all_results.values())
  1128. print(f"读取到 {total_titles} 个标题")
  1129. latest_new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1130. if latest_new_titles:
  1131. total_new_count = sum(len(titles) for titles in latest_new_titles.values())
  1132. print(f"检测到 {total_new_count} 条最新新增新闻")
  1133. word_groups, filter_words = DataProcessor.load_frequency_words()
  1134. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1135. all_results,
  1136. word_groups,
  1137. filter_words,
  1138. id_to_alias,
  1139. title_info,
  1140. self.rank_threshold,
  1141. latest_new_titles,
  1142. )
  1143. html_file = ReportGenerator.generate_html_report(
  1144. stats,
  1145. total_titles,
  1146. is_daily=True,
  1147. new_titles=latest_new_titles,
  1148. id_to_alias=id_to_alias,
  1149. )
  1150. print(f"当日HTML统计报告已生成: {html_file}")
  1151. if self.feishu_report_type in ["daily", "both"]:
  1152. ReportGenerator.send_to_feishu(
  1153. stats, [], "当日汇总", latest_new_titles, id_to_alias
  1154. )
  1155. return html_file
  1156. def run(self) -> None:
  1157. """执行分析流程"""
  1158. now = TimeHelper.get_beijing_time()
  1159. print(f"当前北京时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
  1160. webhook_url = os.environ.get("FEISHU_WEBHOOK_URL", CONFIG["FEISHU_WEBHOOK_URL"])
  1161. if not webhook_url and not CONFIG["CONTINUE_WITHOUT_FEISHU"]:
  1162. print(
  1163. "错误: FEISHU_WEBHOOK_URL未设置且CONTINUE_WITHOUT_FEISHU为False,程序退出"
  1164. )
  1165. return
  1166. if not webhook_url:
  1167. print("FEISHU_WEBHOOK_URL未设置,将继续执行爬虫但不发送飞书通知")
  1168. print(f"飞书报告类型: {self.feishu_report_type}")
  1169. ids = [
  1170. ("toutiao", "今日头条"),
  1171. ("baidu", "百度热搜"),
  1172. ("wallstreetcn-hot", "华尔街见闻"),
  1173. ("thepaper", "澎湃新闻"),
  1174. ("bilibili-hot-search", "bilibili 热搜"),
  1175. ("cls-hot", "财联社热门"),
  1176. ("ifeng", "凤凰网"),
  1177. "tieba",
  1178. "weibo",
  1179. "douyin",
  1180. "zhihu",
  1181. ]
  1182. print(f"开始爬取数据,请求间隔 {self.request_interval} 毫秒")
  1183. FileHelper.ensure_directory_exists("output")
  1184. results, id_to_alias, failed_ids = self.data_fetcher.crawl_websites(
  1185. ids, self.request_interval
  1186. )
  1187. title_file = DataProcessor.save_titles_to_file(results, id_to_alias, failed_ids)
  1188. print(f"标题已保存到: {title_file}")
  1189. new_titles = DataProcessor.detect_latest_new_titles(id_to_alias)
  1190. # 构建标题信息
  1191. time_info = Path(title_file).stem
  1192. title_info = {}
  1193. for source_id, titles_data in results.items():
  1194. title_info[source_id] = {}
  1195. for title, title_data in titles_data.items():
  1196. ranks = title_data.get("ranks", [])
  1197. url = title_data.get("url", "")
  1198. mobile_url = title_data.get("mobileUrl", "")
  1199. title_info[source_id][title] = {
  1200. "first_time": time_info,
  1201. "last_time": time_info,
  1202. "count": 1,
  1203. "ranks": ranks,
  1204. "url": url,
  1205. "mobileUrl": mobile_url,
  1206. }
  1207. word_groups, filter_words = DataProcessor.load_frequency_words()
  1208. stats, total_titles = StatisticsCalculator.count_word_frequency(
  1209. results,
  1210. word_groups,
  1211. filter_words,
  1212. id_to_alias,
  1213. title_info,
  1214. self.rank_threshold,
  1215. new_titles,
  1216. )
  1217. if self.feishu_report_type in ["current", "both"]:
  1218. ReportGenerator.send_to_feishu(
  1219. stats, failed_ids, "单次爬取", new_titles, id_to_alias
  1220. )
  1221. html_file = ReportGenerator.generate_html_report(
  1222. stats, total_titles, failed_ids, False, new_titles, id_to_alias
  1223. )
  1224. print(f"HTML报告已生成: {html_file}")
  1225. daily_html = self.generate_daily_summary()
  1226. if not self.is_github_actions and html_file:
  1227. file_url = "file://" + str(Path(html_file).resolve())
  1228. print(f"正在打开HTML报告: {file_url}")
  1229. webbrowser.open(file_url)
  1230. if daily_html:
  1231. daily_url = "file://" + str(Path(daily_html).resolve())
  1232. print(f"正在打开当日统计报告: {daily_url}")
  1233. webbrowser.open(daily_url)
  1234. def main():
  1235. analyzer = NewsAnalyzer(
  1236. request_interval=CONFIG["REQUEST_INTERVAL"],
  1237. feishu_report_type=CONFIG["FEISHU_REPORT_TYPE"],
  1238. rank_threshold=CONFIG["RANK_THRESHOLD"],
  1239. )
  1240. analyzer.run()
  1241. if __name__ == "__main__":
  1242. main()