crawler_gzh.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from __future__ import annotations
  2. import asyncio
  3. import json
  4. import time
  5. import traceback
  6. from datetime import datetime
  7. from typing import List, Dict
  8. from applications.api import feishu_robot
  9. from applications.crawler.wechat import search
  10. from applications.crawler.wechat import get_article_detail
  11. from applications.crawler.wechat import get_article_list_from_account
  12. from applications.pipeline import CrawlerPipeline
  13. from applications.utils import timestamp_to_str, show_desc_to_sta, generate_gzh_id
  14. class CrawlerGzhConst:
  15. PLATFORM = "weixin"
  16. DEFAULT_VIEW_COUNT = 0
  17. DEFAULT_LIKE_COUNT = 0
  18. DEFAULT_ARTICLE_STATUS = 1
  19. DEFAULT_TIMESTAMP = 1735660800
  20. class CrawlerGzhStrategy(CrawlerPipeline, CrawlerGzhConst):
  21. def __init__(self, pool, log_client, trace_id):
  22. super().__init__(pool, log_client)
  23. self.trace_id = trace_id
  24. async def get_crawler_accounts(self, method: str, strategy: str) -> List[Dict]:
  25. """get crawler accounts"""
  26. match strategy:
  27. case "V1":
  28. query = """
  29. select gh_id, account_name, latest_update_time
  30. from long_articles_accounts
  31. where account_category = %s and is_using = %s and daily_scrape = %s;
  32. """
  33. return await self.pool.async_fetch(query=query, params=(method, 1, 1))
  34. case "V2":
  35. query = """
  36. select gh_id, account_name, latest_update_time
  37. from long_articles_accounts
  38. where account_category = %s and is_using = %s order by recent_score_ci_lower desc limit %s;
  39. """
  40. return await self.pool.async_fetch(
  41. query=query, params=(method, 1, 100)
  42. )
  43. case _:
  44. raise Exception("strategy not supported")
  45. async def get_account_latest_update_timestamp(self, account_id: str) -> int:
  46. """get latest update time"""
  47. query = """ select max(publish_time) as publish_time from crawler_meta_article where out_account_id = %s;"""
  48. latest_timestamp_obj = await self.pool.async_fetch(
  49. query=query, params=(account_id,)
  50. )
  51. return latest_timestamp_obj[0]["publish_time"] if latest_timestamp_obj else None
  52. async def crawl_each_article(
  53. self, article_raw_data, mode, account_method, account_id
  54. ):
  55. """crawl each article"""
  56. base_item = {
  57. "platform": self.PLATFORM,
  58. "mode": mode,
  59. "crawler_time": int(time.time()),
  60. }
  61. match mode:
  62. case "account":
  63. show_stat = show_desc_to_sta(article_raw_data["ShowDesc"])
  64. show_view_count = show_stat.get(
  65. "show_view_count", self.DEFAULT_VIEW_COUNT
  66. )
  67. show_like_count = show_stat.get(
  68. "show_like_count", self.DEFAULT_LIKE_COUNT
  69. )
  70. unique_idx = generate_gzh_id(article_raw_data["ContentUrl"])
  71. new_item = {
  72. **base_item,
  73. "read_cnt": show_view_count,
  74. "like_cnt": show_like_count,
  75. "title": article_raw_data["Title"],
  76. "category": account_method,
  77. "out_account_id": account_id,
  78. "article_index": article_raw_data["ItemIndex"],
  79. "link": article_raw_data["ContentUrl"],
  80. "description": article_raw_data["Digest"],
  81. "unique_index": unique_idx,
  82. "publish_time": article_raw_data["send_time"],
  83. }
  84. case _:
  85. raise Exception(f"unknown mode: {mode}")
  86. await self.save_item_to_database(
  87. media_type="article", item=new_item, trace_id=self.trace_id
  88. )
  89. class CrawlerGzhAccountArticles(CrawlerGzhStrategy):
  90. def __init__(self, pool, log_client, trace_id):
  91. super().__init__(pool, log_client, trace_id)
  92. async def insert_article_into_meta(self, gh_id, account_method, msg_list):
  93. """
  94. 将数据更新到数据库
  95. :return:
  96. """
  97. for msg in msg_list:
  98. article_list = msg["AppMsg"]["DetailInfo"]
  99. for obj in article_list:
  100. await self.crawl_each_article(
  101. article_raw_data=obj,
  102. mode="account",
  103. account_method=account_method,
  104. account_id=gh_id,
  105. )
  106. async def update_account_latest_timestamp(self, gh_id):
  107. """update the latest timestamp after crawler"""
  108. latest_timestamp = await self.get_account_latest_update_timestamp(gh_id)
  109. dt_str = timestamp_to_str(latest_timestamp)
  110. query = """update long_articles_accounts set latest_update_time = %s where gh_id = %s;"""
  111. await self.pool.async_save(query=query, params=(dt_str, gh_id))
  112. async def crawler_single_account(self, account_method: str, account: Dict) -> None:
  113. """crawler single account"""
  114. current_cursor = None
  115. gh_id = account["gh_id"]
  116. latest_timestamp = account["latest_update_time"].timestamp()
  117. while True:
  118. # fetch response from weixin
  119. response = get_article_list_from_account(
  120. account_id=gh_id, index=current_cursor
  121. )
  122. msg_list = response.get("data", {}).get("data")
  123. if not msg_list:
  124. break
  125. # process current page
  126. await self.insert_article_into_meta(gh_id, account_method, msg_list)
  127. # whether crawl next page
  128. last_article_in_this_page = msg_list[-1]
  129. last_time_stamp_in_this_msg = last_article_in_this_page["AppMsg"][
  130. "BaseInfo"
  131. ]["UpdateTime"]
  132. if last_time_stamp_in_this_msg > latest_timestamp:
  133. await self.update_account_latest_timestamp(gh_id)
  134. break
  135. # update cursor for next page
  136. current_cursor = response.get("data", {}).get("next_cursor")
  137. if not current_cursor:
  138. break
  139. async def deal(self, method: str, strategy: str = "V1"):
  140. account_list = await self.get_crawler_accounts(method, strategy)
  141. for account in account_list:
  142. print(account)
  143. try:
  144. await self.crawler_single_account(method, account)
  145. except Exception as e:
  146. await self.log_client.log(
  147. contents={
  148. "task": "crawler_gzh_articles",
  149. "trace_id": account["trace_id"],
  150. "data": {
  151. "account_id": account["account_id"],
  152. "account_method": method,
  153. "error": str(e),
  154. "traceback": traceback.format_exc(),
  155. }
  156. }
  157. )
  158. class CrawlerGzhSearchArticles(CrawlerGzhStrategy):
  159. def __init__(self, pool, log_client, trace_id):
  160. super().__init__(pool, log_client, trace_id)
  161. async def deal(self):
  162. return {
  163. "mode": "search",
  164. "message": "still developing"
  165. }