crawler_gzh.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. from __future__ import annotations
  2. import asyncio
  3. import json
  4. import time
  5. import traceback
  6. from datetime import datetime, date
  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. STAT_DURATION = 30 # days
  20. DEFAULT_TIMESTAMP = 1735660800
  21. class CrawlerGzhBaseStrategy(CrawlerPipeline, CrawlerGzhConst):
  22. def __init__(self, pool, log_client, trace_id):
  23. super().__init__(pool, log_client)
  24. self.trace_id = trace_id
  25. async def get_crawler_accounts(self, method: str, strategy: str) -> List[Dict]:
  26. """get crawler accounts"""
  27. match strategy:
  28. case "V1":
  29. query = """
  30. select gh_id, account_name, latest_update_time
  31. from long_articles_accounts
  32. where account_category = %s and is_using = %s and daily_scrape = %s;
  33. """
  34. return await self.pool.async_fetch(query=query, params=(method, 1, 1))
  35. case "V2":
  36. query = """
  37. select gh_id, account_name, latest_update_time
  38. from long_articles_accounts
  39. where account_category = %s and is_using = %s order by recent_score_ci_lower desc limit %s;
  40. """
  41. return await self.pool.async_fetch(query=query, params=(method, 1, 500))
  42. case _:
  43. raise Exception("strategy not supported")
  44. async def get_account_latest_update_timestamp(self, account_id: str) -> int:
  45. """get latest update time"""
  46. query = """ select max(publish_time) as publish_time from crawler_meta_article where out_account_id = %s;"""
  47. latest_timestamp_obj = await self.pool.async_fetch(
  48. query=query, params=(account_id,)
  49. )
  50. return latest_timestamp_obj[0]["publish_time"] if latest_timestamp_obj else None
  51. async def crawl_each_article(
  52. self, article_raw_data, mode, account_method, account_id
  53. ):
  54. """crawl each article"""
  55. base_item = {
  56. "platform": self.PLATFORM,
  57. "mode": mode,
  58. "crawler_time": int(time.time()),
  59. }
  60. match mode:
  61. case "account":
  62. show_stat = show_desc_to_sta(article_raw_data["ShowDesc"])
  63. show_view_count = show_stat.get(
  64. "show_view_count", self.DEFAULT_VIEW_COUNT
  65. )
  66. show_like_count = show_stat.get(
  67. "show_like_count", self.DEFAULT_LIKE_COUNT
  68. )
  69. unique_idx = generate_gzh_id(article_raw_data["ContentUrl"])
  70. new_item = {
  71. **base_item,
  72. "read_cnt": show_view_count,
  73. "like_cnt": show_like_count,
  74. "title": article_raw_data["Title"],
  75. "category": account_method,
  76. "out_account_id": account_id,
  77. "article_index": article_raw_data["ItemIndex"],
  78. "link": article_raw_data["ContentUrl"],
  79. "description": article_raw_data["Digest"],
  80. "unique_index": unique_idx,
  81. "publish_time": article_raw_data["send_time"],
  82. }
  83. case _:
  84. raise Exception(f"unknown mode: {mode}")
  85. await self.save_item_to_database(
  86. media_type="article", item=new_item, trace_id=self.trace_id
  87. )
  88. async def update_account_read_avg_info(self, gh_id, account_name):
  89. """update account read avg info"""
  90. position_list = [i for i in range(1, 9)]
  91. today_dt = date.today().isoformat()
  92. for position in position_list:
  93. query = """
  94. select read_cnt, from_unixtime(publish_time, '%Y-%m_%d') as publish_dt from crawler_meta_article
  95. where out_account_id = %s and article_index = %s
  96. order by publish_time desc limit %s;
  97. """
  98. fetch_response = await self.pool.async_fetch(
  99. query=query, params=(gh_id, position, self.STAT_DURATION)
  100. )
  101. if fetch_response:
  102. read_cnt_list = [i["read_cnt"] for i in fetch_response]
  103. n = len(read_cnt_list)
  104. read_avg = sum(read_cnt_list) / n
  105. max_publish_dt = fetch_response[0]["publish_dt"]
  106. remark = f"从{max_publish_dt}开始计算,往前算{len(fetch_response)}天"
  107. insert_query = f"""
  108. insert ignore into crawler_meta_article_accounts_read_avg
  109. (gh_id, account_name, position, read_avg, dt, status, remark)
  110. values
  111. (%s, %s, %s, %s, %s, %s, %s);
  112. """
  113. insert_rows = await self.pool.async_save(
  114. query=insert_query,
  115. params=(
  116. gh_id,
  117. account_name,
  118. position,
  119. read_avg,
  120. today_dt,
  121. 1,
  122. remark,
  123. ),
  124. )
  125. if insert_rows:
  126. update_query = f"""
  127. update crawler_meta_article_accounts_read_avg
  128. set status = %s
  129. where gh_id = %s and position = %s and dt < %s;
  130. """
  131. self.pool.async_save(update_query, (0, gh_id, position, today_dt))
  132. class CrawlerGzhAccountArticles(CrawlerGzhBaseStrategy):
  133. def __init__(self, pool, log_client, trace_id):
  134. super().__init__(pool, log_client, trace_id)
  135. async def insert_article_into_meta(self, gh_id, account_method, msg_list):
  136. """
  137. 将数据更新到数据库
  138. :return:
  139. """
  140. for msg in msg_list:
  141. article_list = msg["AppMsg"]["DetailInfo"]
  142. for obj in article_list:
  143. await self.crawl_each_article(
  144. article_raw_data=obj,
  145. mode="account",
  146. account_method=account_method,
  147. account_id=gh_id,
  148. )
  149. async def update_account_latest_timestamp(self, gh_id):
  150. """update the latest timestamp after crawler"""
  151. latest_timestamp = await self.get_account_latest_update_timestamp(gh_id)
  152. dt_str = timestamp_to_str(latest_timestamp)
  153. query = """update long_articles_accounts set latest_update_time = %s where gh_id = %s;"""
  154. await self.pool.async_save(query=query, params=(dt_str, gh_id))
  155. async def crawler_single_account(self, account_method: str, account: Dict) -> None:
  156. """crawler single account"""
  157. current_cursor = None
  158. gh_id = account["gh_id"]
  159. latest_timestamp = account["latest_update_time"].timestamp()
  160. while True:
  161. # fetch response from weixin
  162. response = get_article_list_from_account(
  163. account_id=gh_id, index=current_cursor
  164. )
  165. msg_list = response.get("data", {}).get("data")
  166. if not msg_list:
  167. break
  168. # process current page
  169. await self.insert_article_into_meta(gh_id, account_method, msg_list)
  170. # whether crawl next page
  171. last_article_in_this_page = msg_list[-1]
  172. last_time_stamp_in_this_msg = last_article_in_this_page["AppMsg"][
  173. "BaseInfo"
  174. ]["UpdateTime"]
  175. if last_time_stamp_in_this_msg > latest_timestamp:
  176. await self.update_account_latest_timestamp(gh_id)
  177. break
  178. # update cursor for next page
  179. current_cursor = response.get("data", {}).get("next_cursor")
  180. if not current_cursor:
  181. break
  182. async def deal(self, method: str, strategy: str = "V1"):
  183. account_list = await self.get_crawler_accounts(method, strategy)
  184. for account in account_list:
  185. print(account)
  186. try:
  187. await self.crawler_single_account(method, account)
  188. await self.update_account_read_avg_info(
  189. gh_id=account["gh_id"], account_name=account["account_name"]
  190. )
  191. except Exception as e:
  192. await self.log_client.log(
  193. contents={
  194. "task": "crawler_gzh_articles",
  195. "trace_id": self.trace_id,
  196. "data": {
  197. "account_id": account["account_id"],
  198. "account_method": method,
  199. "error": str(e),
  200. "traceback": traceback.format_exc(),
  201. },
  202. }
  203. )
  204. class CrawlerGzhSearchArticles(CrawlerGzhBaseStrategy):
  205. def __init__(self, pool, log_client, trace_id):
  206. super().__init__(pool, log_client, trace_id)
  207. async def deal(self):
  208. return {"mode": "search", "message": "still developing"}