weixin_video_crawler.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """
  2. @author: luojunhui
  3. 抓取视频
  4. """
  5. import json
  6. import time
  7. import traceback
  8. from typing import List, Dict
  9. from tqdm import tqdm
  10. from pymysql.cursors import DictCursor
  11. from config import apolloConfig
  12. from applications import bot
  13. from applications import log
  14. from applications import Functions
  15. from applications import WeixinSpider
  16. from applications import longArticlesMySQL
  17. from applications.const import WeixinVideoCrawlerConst
  18. spider = WeixinSpider()
  19. functions = Functions()
  20. config = apolloConfig(env="prod")
  21. const = WeixinVideoCrawlerConst()
  22. class WeixinVideoCrawler(object):
  23. """
  24. 微信视频抓取
  25. """
  26. def __init__(self):
  27. self.db_client = longArticlesMySQL()
  28. self.festival_list = json.loads(config.getConfigValue("festival"))
  29. def is_festival(self, title: str) -> bool:
  30. """
  31. 判断是否为节假日
  32. :param title:
  33. :return:
  34. """
  35. for festival in self.festival_list:
  36. if festival in title:
  37. return True
  38. return False
  39. def get_title_status(self, title: str) -> int:
  40. """
  41. 通过标题获取文章状态
  42. :param title:
  43. :return:
  44. """
  45. if self.is_festival(title):
  46. return const.TITLE_FESTIVAL_STATUS
  47. elif len(title) < const.TITLE_MIN_LENGTH:
  48. return const.TITLE_SHORT_STATUS
  49. else:
  50. return const.TITLE_DEFAULT_STATUS
  51. def update_account_latest_crawler_timestamp(self, gh_id: str) -> int:
  52. """
  53. 更新最新抓取时间戳
  54. :param gh_id:
  55. :return:
  56. """
  57. update_sql = f"""
  58. UPDATE weixin_account_for_videos
  59. SET latest_crawler_timestamp = (
  60. SELECT max(publish_timestamp)
  61. FROM publish_single_video_source
  62. WHERE out_account_id = %s
  63. )
  64. WHERE gh_id = %s;
  65. """
  66. affected_rows = self.db_client.update(
  67. sql=update_sql,
  68. params=(gh_id, gh_id)
  69. )
  70. return affected_rows
  71. def get_crawler_accounts(self) -> List[Dict]:
  72. """
  73. 获取微信公众号列表
  74. :return:
  75. """
  76. select_sql = f"""
  77. SELECT gh_id, account_name, latest_crawler_timestamp
  78. FROM weixin_account_for_videos
  79. WHERE status = {const.ACCOUNT_CRAWL_STATUS};
  80. """
  81. response = self.db_client.select(select_sql, DictCursor)
  82. return response
  83. def crawler_article_video_list(self, account_obj: Dict, cursor=None):
  84. """
  85. 抓取单个账号的文章列表,获取视频
  86. :param cursor:
  87. :param account_obj:
  88. :return: 返回待下载的视频列表
  89. """
  90. gh_id = account_obj["gh_id"]
  91. account_name = account_obj["account_name"]
  92. latest_crawler_timestamp = account_obj["latest_crawler_timestamp"]
  93. if latest_crawler_timestamp is None:
  94. latest_crawler_timestamp = const.DEFAULT_TIMESTAMP
  95. # 调用爬虫接口
  96. response = spider.update_msg_list(gh_id, index=cursor)
  97. if response['code'] == const.REQUEST_SUCCESS:
  98. # 一般返回最近10天的msg_list
  99. msg_list = response.get('data', {}).get("data", [])
  100. if msg_list:
  101. last_msg = msg_list[-1]
  102. last_msg_base_info = last_msg['AppMsg']['BaseInfo']
  103. last_msg_create_timestamp = last_msg_base_info['CreateTime']
  104. self.insert_msg_list(account_name=account_name, gh_id=gh_id, msg_list=msg_list)
  105. if last_msg_create_timestamp > latest_crawler_timestamp:
  106. next_cursor = response['data']['next_cursor']
  107. return self.crawler_article_video_list(account_obj=account_obj, cursor=next_cursor)
  108. else:
  109. return []
  110. else:
  111. return []
  112. return []
  113. def is_downloaded(self, url_unique: str) -> bool:
  114. """
  115. 判断该视频是否已经下载
  116. :param url_unique:
  117. :return:
  118. """
  119. select_sql = f"""
  120. SELECT id
  121. FROM publish_single_video_source
  122. WHERE url_unique_md5 = '{url_unique}';
  123. """
  124. response = self.db_client.select(select_sql)
  125. if response:
  126. return True
  127. else:
  128. return False
  129. def insert_msg_list(self, account_name, gh_id, msg_list: List[Dict]) -> None:
  130. """
  131. 插入视频信息
  132. :param gh_id:
  133. :param account_name:
  134. :param msg_list:
  135. :return:
  136. """
  137. for info in msg_list:
  138. create_time = info.get("AppMsg", {}).get("BaseInfo", {}).get("CreateTime", None)
  139. publish_type = info.get("AppMsg", {}).get("BaseInfo", {}).get("Type", None)
  140. detail_article_list = info.get("AppMsg", {}).get("DetailInfo", [])
  141. if detail_article_list:
  142. for article in tqdm(detail_article_list, desc="{}: crawler_in_msg_list".format(account_name)):
  143. article_url = article.get("ContentUrl", None)
  144. url_unique = functions.generateGzhId(article_url)
  145. # 判断该视频链接是否下载,若已经下载则直接跳过
  146. if self.is_downloaded(url_unique):
  147. continue
  148. try:
  149. download_path = functions.download_gzh_video(article_url)
  150. if download_path:
  151. oss_path = functions.upload_to_oss(local_video_path=download_path)
  152. title = article.get("Title", None)
  153. position = article.get("ItemIndex", None)
  154. cover_url = article.get("CoverImgUrl", None)
  155. show_desc = article.get("ShowDesc", None)
  156. show_stat = functions.show_desc_to_sta(show_desc)
  157. read_cnt = show_stat.get("show_view_count", 0)
  158. like_cnt = show_stat.get("show_like_count", 0)
  159. title_status = self.get_title_status(title)
  160. insert_sql = f"""
  161. INSERT INTO publish_single_video_source
  162. (content_trace_id, article_title, out_account_id, out_account_name, read_cnt, like_cnt, article_index, article_publish_type, article_url, cover_url, video_oss_path, bad_status, publish_timestamp, crawler_timestamp, url_unique_md5)
  163. values
  164. (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
  165. """
  166. try:
  167. self.db_client.update(
  168. sql=insert_sql,
  169. params=(
  170. "video" + url_unique,
  171. title,
  172. gh_id,
  173. account_name,
  174. read_cnt,
  175. like_cnt,
  176. position,
  177. publish_type,
  178. article_url,
  179. cover_url,
  180. oss_path,
  181. title_status,
  182. create_time,
  183. int(time.time()),
  184. url_unique
  185. )
  186. )
  187. log(
  188. task='weixin_video_crawler',
  189. function="insert_msg_list",
  190. message="插入一条视频",
  191. data={"account_name": account_name, "url": article_url}
  192. )
  193. except Exception as e:
  194. try:
  195. update_sql = f"""
  196. UPDATE publish_single_video_source
  197. SET read_cnt = %s, like_cnt = %s
  198. WHERE url_unique_md5 = %s;
  199. """
  200. self.db_client.update(
  201. sql=update_sql,
  202. params=(read_cnt, like_cnt, functions.generateGzhId(article_url))
  203. )
  204. except Exception as e:
  205. error_stack = traceback.format_exc()
  206. log(
  207. task='weixin_video_crawler',
  208. function="update_msg_list",
  209. status="fail",
  210. message="更新内容失败",
  211. data={"error": str(e), "error_stack": error_stack, "url": article_url}
  212. )
  213. else:
  214. continue
  215. except Exception as e:
  216. error_stack = traceback.format_exc()
  217. log(
  218. task='weixin_video_crawler',
  219. function="update_msg_list",
  220. status="fail",
  221. message="更新内容失败",
  222. data={"error": str(e), "error_stack": error_stack, "url": article_url}
  223. )
  224. def crawler_task(self):
  225. """
  226. 抓取任务
  227. :return:
  228. """
  229. account_list = self.get_crawler_accounts()
  230. for account_obj in tqdm(account_list, desc="crawler_video_for_each_account"):
  231. try:
  232. self.crawler_article_video_list(account_obj)
  233. self.update_account_latest_crawler_timestamp(gh_id=account_obj["gh_id"])
  234. time.sleep(const.SLEEP_SECONDS)
  235. except Exception as e:
  236. error_stack = traceback.format_exc()
  237. log(
  238. task='weixin_video_crawler',
  239. function="crawler_task",
  240. status="fail",
  241. message="抓取任务失败--单账号",
  242. data={"error": str(e), "error_stack": error_stack, "account_name": account_obj["account_name"]}
  243. )
  244. def mention(self, start_timestamp):
  245. """
  246. 飞书发送消息
  247. :param start_timestamp:
  248. :return:
  249. """
  250. sql = f"""select count(1) from publish_single_video_source where crawler_timestamp >= {start_timestamp};"""
  251. response = self.db_client.select(sql)
  252. new_articles_count = response[0][0]
  253. bot(
  254. title='微信抓取任务执行完成',
  255. detail={
  256. "新增视频数量": new_articles_count
  257. }
  258. )
  259. def run(self):
  260. """
  261. 执行任务
  262. :return:
  263. """
  264. start_timestamp = int(time.time())
  265. self.crawler_task()
  266. self.mention(start_timestamp)