crawler_gzh.py 14 KB

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