main.py 58 KB

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