crawler_gzh.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. from __future__ import annotations
  2. import asyncio
  3. import json
  4. import time
  5. import traceback
  6. from datetime import datetime, date, timedelta
  7. from typing import List, Dict
  8. from applications.api import feishu_robot
  9. from applications.crawler.wechat import weixin_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
  14. from applications.utils import get_hot_titles, generate_gzh_id
  15. class CrawlerGzhConst:
  16. PLATFORM = "weixin"
  17. DEFAULT_VIEW_COUNT = 0
  18. DEFAULT_LIKE_COUNT = 0
  19. DEFAULT_ARTICLE_STATUS = 1
  20. MAX_DEPTH = 3
  21. #
  22. SLEEP_SECONDS = 1
  23. STAT_DURATION = 30 # days
  24. DEFAULT_TIMESTAMP = 1735660800
  25. class CrawlerGzhBaseStrategy(CrawlerPipeline, CrawlerGzhConst):
  26. def __init__(self, pool, log_client, trace_id):
  27. super().__init__(pool, log_client)
  28. self.trace_id = trace_id
  29. async def get_crawler_accounts(self, method: str, strategy: str) -> List[Dict]:
  30. """get crawler accounts"""
  31. match strategy:
  32. case "V1":
  33. query = """
  34. select gh_id, account_name, latest_update_time
  35. from long_articles_accounts
  36. where account_category = %s and is_using = %s and daily_scrape = %s;
  37. """
  38. return await self.pool.async_fetch(query=query, params=(method, 1, 1))
  39. case "V2":
  40. query = """
  41. select gh_id, account_name, latest_update_time
  42. from long_articles_accounts
  43. where account_category = %s and is_using = %s order by recent_score_ci_lower desc limit %s;
  44. """
  45. return await self.pool.async_fetch(query=query, params=(method, 1, 500))
  46. case _:
  47. raise Exception("strategy not supported")
  48. async def get_account_latest_update_timestamp(self, account_id: str) -> int:
  49. """get latest update time"""
  50. query = """ select max(publish_time) as publish_time from crawler_meta_article where out_account_id = %s;"""
  51. latest_timestamp_obj = await self.pool.async_fetch(
  52. query=query, params=(account_id,)
  53. )
  54. return latest_timestamp_obj[0]["publish_time"] if latest_timestamp_obj else None
  55. async def crawl_each_article(
  56. self, article_raw_data, mode, account_method, account_id, source_title=None
  57. ):
  58. """crawl each article"""
  59. base_item = {
  60. "platform": self.PLATFORM,
  61. "mode": mode,
  62. "crawler_time": int(time.time()),
  63. "category": account_method,
  64. }
  65. match mode:
  66. case "account":
  67. show_stat = show_desc_to_sta(article_raw_data["ShowDesc"])
  68. show_view_count = show_stat.get(
  69. "show_view_count", self.DEFAULT_VIEW_COUNT
  70. )
  71. show_like_count = show_stat.get(
  72. "show_like_count", self.DEFAULT_LIKE_COUNT
  73. )
  74. unique_idx = generate_gzh_id(article_raw_data["ContentUrl"])
  75. new_item = {
  76. **base_item,
  77. "read_cnt": show_view_count,
  78. "like_cnt": show_like_count,
  79. "title": article_raw_data["Title"],
  80. "out_account_id": account_id,
  81. "article_index": article_raw_data["ItemIndex"],
  82. "link": article_raw_data["ContentUrl"],
  83. "description": article_raw_data["Digest"],
  84. "unique_index": unique_idx,
  85. "publish_time": article_raw_data["send_time"],
  86. }
  87. case "search":
  88. new_item = {
  89. **base_item,
  90. "out_account_id": account_id,
  91. "article_index": article_raw_data["item_index"],
  92. "title": article_raw_data["title"],
  93. "link": article_raw_data["content_link"],
  94. "like_cnt": article_raw_data.get(
  95. "like_count", self.DEFAULT_LIKE_COUNT
  96. ),
  97. "read_cnt": article_raw_data.get(
  98. "view_count", self.DEFAULT_VIEW_COUNT
  99. ),
  100. "publish_time": int(article_raw_data["publish_timestamp"] / 1000),
  101. "unique_index": generate_gzh_id(article_raw_data["content_link"]),
  102. "source_article_title": source_title,
  103. }
  104. case _:
  105. raise Exception(f"unknown mode: {mode}")
  106. await self.save_item_to_database(
  107. media_type="article", item=new_item, trace_id=self.trace_id
  108. )
  109. await asyncio.sleep(self.STAT_DURATION)
  110. async def update_account_read_avg_info(self, gh_id, account_name):
  111. """update account read avg info"""
  112. position_list = [i for i in range(1, 9)]
  113. today_dt = date.today().isoformat()
  114. for position in position_list:
  115. query = f"""
  116. select read_cnt, from_unixtime(publish_time, "%Y-%m_%d") as publish_dt from crawler_meta_article
  117. where out_account_id = '{gh_id}' and article_index = {position}
  118. order by publish_time desc limit {self.STAT_DURATION};
  119. """
  120. fetch_response = await self.pool.async_fetch(query=query)
  121. if fetch_response:
  122. read_cnt_list = [i["read_cnt"] for i in fetch_response]
  123. n = len(read_cnt_list)
  124. read_avg = sum(read_cnt_list) / n
  125. max_publish_dt = fetch_response[0]["publish_dt"]
  126. remark = f"从{max_publish_dt}开始计算,往前算{len(fetch_response)}天"
  127. insert_query = f"""
  128. insert ignore into crawler_meta_article_accounts_read_avg
  129. (gh_id, account_name, position, read_avg, dt, status, remark)
  130. values
  131. (%s, %s, %s, %s, %s, %s, %s);
  132. """
  133. insert_rows = await self.pool.async_save(
  134. query=insert_query,
  135. params=(
  136. gh_id,
  137. account_name,
  138. position,
  139. read_avg,
  140. today_dt,
  141. 1,
  142. remark,
  143. ),
  144. )
  145. if insert_rows:
  146. update_query = f"""
  147. update crawler_meta_article_accounts_read_avg
  148. set status = %s
  149. where gh_id = %s and position = %s and dt < %s;
  150. """
  151. await self.pool.async_save(
  152. update_query, (0, gh_id, position, today_dt)
  153. )
  154. async def get_hot_titles_with_strategy(self, strategy):
  155. """get hot titles with strategy"""
  156. match strategy:
  157. case "V1":
  158. position = 3
  159. read_times_threshold = 1.21
  160. timedelta_days = 3
  161. case "V2":
  162. position = 2
  163. read_times_threshold = 1.1
  164. timedelta_days = 5
  165. case _:
  166. raise Exception(f"unknown strategy: {strategy}")
  167. date_string = (datetime.today() - timedelta(days=timedelta_days)).strftime(
  168. "%Y-%m-%d"
  169. )
  170. return await get_hot_titles(
  171. self.pool,
  172. date_string=date_string,
  173. position=position,
  174. read_times_threshold=read_times_threshold,
  175. )
  176. class CrawlerGzhAccountArticles(CrawlerGzhBaseStrategy):
  177. def __init__(self, pool, log_client, trace_id):
  178. super().__init__(pool, log_client, trace_id)
  179. async def insert_article_into_meta(self, gh_id, account_method, msg_list):
  180. """
  181. 将数据更新到数据库
  182. :return:
  183. """
  184. for msg in msg_list:
  185. article_list = msg["AppMsg"]["DetailInfo"]
  186. for obj in article_list:
  187. await self.crawl_each_article(
  188. article_raw_data=obj,
  189. mode="account",
  190. account_method=account_method,
  191. account_id=gh_id,
  192. )
  193. async def update_account_latest_timestamp(self, gh_id):
  194. """update the latest timestamp after crawler"""
  195. latest_timestamp = await self.get_account_latest_update_timestamp(gh_id)
  196. dt_str = timestamp_to_str(latest_timestamp)
  197. query = """update long_articles_accounts set latest_update_time = %s where gh_id = %s;"""
  198. await self.pool.async_save(query=query, params=(dt_str, gh_id))
  199. async def crawler_single_account(self, account_method: str, account: Dict) -> None:
  200. """crawler single account"""
  201. current_cursor = None
  202. gh_id = account["gh_id"]
  203. latest_timestamp = account["latest_update_time"].timestamp()
  204. while True:
  205. # fetch response from weixin
  206. response = await get_article_list_from_account(
  207. account_id=gh_id, index=current_cursor
  208. )
  209. msg_list = response.get("data", {}).get("data")
  210. if not msg_list:
  211. break
  212. # process current page
  213. await self.insert_article_into_meta(gh_id, account_method, msg_list)
  214. # whether crawl next page
  215. last_article_in_this_page = msg_list[-1]
  216. last_time_stamp_in_this_msg = last_article_in_this_page["AppMsg"][
  217. "BaseInfo"
  218. ]["UpdateTime"]
  219. if last_time_stamp_in_this_msg > latest_timestamp:
  220. await self.update_account_latest_timestamp(gh_id)
  221. break
  222. # update cursor for next page
  223. current_cursor = response.get("data", {}).get("next_cursor")
  224. if not current_cursor:
  225. break
  226. async def deal(self, method: str, strategy: str = "V1"):
  227. account_list = await self.get_crawler_accounts(method, strategy)
  228. for account in account_list:
  229. print(account)
  230. try:
  231. await self.crawler_single_account(method, account)
  232. await self.update_account_read_avg_info(
  233. gh_id=account["gh_id"], account_name=account["account_name"]
  234. )
  235. except Exception as e:
  236. await self.log_client.log(
  237. contents={
  238. "task": "crawler_gzh_articles",
  239. "trace_id": self.trace_id,
  240. "data": {
  241. "account_id": account["gh_id"],
  242. "account_method": method,
  243. "error": str(e),
  244. "traceback": traceback.format_exc(),
  245. },
  246. }
  247. )
  248. class CrawlerGzhSearchArticles(CrawlerGzhBaseStrategy):
  249. def __init__(self, pool, log_client, trace_id):
  250. super().__init__(pool, log_client, trace_id)
  251. async def crawl_search_articles_detail(
  252. self, article_list: List[Dict], source_title: str
  253. ):
  254. for article in article_list:
  255. url = article["url"]
  256. detail_response = await get_article_detail(url, is_count=True, is_cache=False)
  257. if not detail_response:
  258. continue
  259. article_data = detail_response.get("data")
  260. if not article_data:
  261. continue
  262. if type(article_data) is not dict:
  263. continue
  264. article_detail = article_data.get("data")
  265. if not article_detail:
  266. continue
  267. await self.crawl_each_article(
  268. article_raw_data=article_detail,
  269. mode="search",
  270. account_method="search",
  271. account_id="search",
  272. source_title=source_title,
  273. )
  274. await asyncio.sleep(self.SLEEP_SECONDS)
  275. async def search_each_title(self, title: str, page: str = "1") -> None:
  276. """search in weixin"""
  277. current_page = page
  278. while True:
  279. # 翻页不超过3页
  280. if int(current_page) > self.MAX_DEPTH:
  281. break
  282. # 调用搜索接口
  283. search_response = await weixin_search(keyword=title, page=page)
  284. if not search_response:
  285. break
  286. article_list = search_response.get("data", {}).get("data")
  287. if not article_list:
  288. break
  289. # 存储搜索结果
  290. await self.crawl_search_articles_detail(article_list, title)
  291. # 判断是否还有下一页
  292. has_more = search_response.get("data", {}).get("has_more")
  293. if not has_more:
  294. break
  295. # 更新page
  296. current_page = search_response.get("data", {}).get("next_cursor")
  297. async def deal(self, strategy: str = "V1"):
  298. hot_titles = await self.get_hot_titles_with_strategy(strategy)
  299. for hot_title in hot_titles:
  300. print("hot title:", hot_title)
  301. await self.search_each_title(hot_title)