xiaoniangao_hour_scheduling.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/3/15
  4. import datetime
  5. import json
  6. import os
  7. import random
  8. import shutil
  9. import sys
  10. import time
  11. import requests
  12. import urllib3
  13. sys.path.append(os.getcwd())
  14. from common.common import Common
  15. from common.feishu import Feishu
  16. from common.publish import Publish
  17. from common.scheduling_db import MysqlHelper
  18. from common.public import get_config_from_mysql
  19. proxies = {"http": None, "https": None}
  20. class XiaoniangaoHourScheduling:
  21. platform = "小年糕"
  22. words = "abcdefghijklmnopqrstuvwxyz0123456789"
  23. uid = f"""{"".join(random.sample(words, 8))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 12))}"""
  24. token = "".join(random.sample(words, 32))
  25. uid_token_dict = {
  26. "uid": uid,
  27. "token": token
  28. }
  29. # 生成 uid、token
  30. @classmethod
  31. def get_uid_token(cls):
  32. words = "abcdefghijklmnopqrstuvwxyz0123456789"
  33. uid = f"""{"".join(random.sample(words, 8))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 4))}-{"".join(random.sample(words, 12))}"""
  34. token = "".join(random.sample(words, 32))
  35. uid_token_dict = {
  36. "uid": uid,
  37. "token": token
  38. }
  39. return uid_token_dict
  40. # 基础门槛规则
  41. @staticmethod
  42. def download_rule(log_type, crawler, video_dict, rule_dict):
  43. """
  44. 下载视频的基本规则
  45. :param log_type: 日志
  46. :param crawler: 哪款爬虫
  47. :param video_dict: 视频信息,字典格式
  48. :param rule_dict: 规则信息,字典格式
  49. :return: 满足规则,返回 True;反之,返回 False
  50. """
  51. rule_play_cnt_min = rule_dict.get('play_cnt', {}).get('min', 0)
  52. rule_play_cnt_max = rule_dict.get('play_cnt', {}).get('max', 100000000)
  53. if rule_play_cnt_max == 0:
  54. rule_play_cnt_max = 100000000
  55. rule_duration_min = rule_dict.get('duration', {}).get('min', 0)
  56. rule_duration_max = rule_dict.get('duration', {}).get('max', 100000000)
  57. if rule_duration_max == 0:
  58. rule_duration_max = 100000000
  59. rule_period_min = rule_dict.get('period', {}).get('min', 0)
  60. # rule_period_max = rule_dict.get('period', {}).get('max', 100000000)
  61. # if rule_period_max == 0:
  62. # rule_period_max = 100000000
  63. rule_fans_cnt_min = rule_dict.get('fans_cnt', {}).get('min', 0)
  64. rule_fans_cnt_max = rule_dict.get('fans_cnt', {}).get('max', 100000000)
  65. if rule_fans_cnt_max == 0:
  66. rule_fans_cnt_max = 100000000
  67. rule_videos_cnt_min = rule_dict.get('videos_cnt', {}).get('min', 0)
  68. rule_videos_cnt_max = rule_dict.get('videos_cnt', {}).get('max', 100000000)
  69. if rule_videos_cnt_max == 0:
  70. rule_videos_cnt_max = 100000000
  71. rule_like_cnt_min = rule_dict.get('like_cnt', {}).get('min', 0)
  72. rule_like_cnt_max = rule_dict.get('like_cnt', {}).get('max', 100000000)
  73. if rule_like_cnt_max == 0:
  74. rule_like_cnt_max = 100000000
  75. rule_width_min = rule_dict.get('width', {}).get('min', 0)
  76. rule_width_max = rule_dict.get('width', {}).get('max', 100000000)
  77. if rule_width_max == 0:
  78. rule_width_max = 100000000
  79. rule_height_min = rule_dict.get('height', {}).get('min', 0)
  80. rule_height_max = rule_dict.get('height', {}).get('max', 100000000)
  81. if rule_height_max == 0:
  82. rule_height_max = 100000000
  83. rule_share_cnt_min = rule_dict.get('share_cnt', {}).get('min', 0)
  84. rule_share_cnt_max = rule_dict.get('share_cnt', {}).get('max', 100000000)
  85. if rule_share_cnt_max == 0:
  86. rule_share_cnt_max = 100000000
  87. rule_comment_cnt_min = rule_dict.get('comment_cnt', {}).get('min', 0)
  88. rule_comment_cnt_max = rule_dict.get('comment_cnt', {}).get('max', 100000000)
  89. if rule_comment_cnt_max == 0:
  90. rule_comment_cnt_max = 100000000
  91. rule_publish_time_min = rule_dict.get('publish_time', {}).get('min', 0)
  92. rule_publish_time_max = rule_dict.get('publish_time', {}).get('max', 0)
  93. if rule_publish_time_max == 0:
  94. rule_publish_time_max = 4102415999000 # 2099-12-31 23:59:59
  95. Common.logger(log_type, crawler).info(
  96. f'rule_duration_max:{rule_duration_max} >= duration:{int(float(video_dict["duration"]))} >= rule_duration_min:{int(rule_duration_min)}')
  97. Common.logger(log_type, crawler).info(
  98. f'rule_play_cnt_max:{int(rule_play_cnt_max)} >= play_cnt:{int(video_dict["play_cnt"])} >= rule_play_cnt_min:{int(rule_play_cnt_min)}')
  99. Common.logger(log_type, crawler).info(
  100. f'now:{int(time.time())} - publish_time_stamp:{int(video_dict["publish_time_stamp"])} <= {3600 * 24 * int(rule_period_min)}')
  101. Common.logger(log_type, crawler).info(
  102. f'rule_like_cnt_max:{int(rule_like_cnt_max)} >= like_cnt:{int(video_dict["like_cnt"])} >= rule_like_cnt_min:{int(rule_like_cnt_min)}')
  103. Common.logger(log_type, crawler).info(
  104. f'rule_comment_cnt_max:{int(rule_comment_cnt_max)} >= comment_cnt:{int(video_dict["comment_cnt"])} >= rule_comment_cnt_min:{int(rule_comment_cnt_min)}')
  105. Common.logger(log_type, crawler).info(
  106. f'rule_share_cnt_max:{int(rule_share_cnt_max)} >= share_cnt:{int(video_dict["share_cnt"])} >= rule_share_cnt_min:{int(rule_share_cnt_min)}')
  107. Common.logger(log_type, crawler).info(
  108. f'rule_width_max:{int(rule_width_max)} >= video_width:{int(video_dict["video_width"])} >= rule_width_min:{int(rule_width_min)}')
  109. Common.logger(log_type, crawler).info(
  110. f'rule_height_max:{int(rule_height_max)} >= video_height:{int(video_dict["video_height"])} >= rule_height_min:{int(rule_height_min)}')
  111. Common.logger(log_type, crawler).info(
  112. f'rule_publish_time_max:{int(rule_publish_time_max)} >= publish_time_stamp:{int(video_dict["publish_time_stamp"])} >= rule_publish_time_min:{int(rule_publish_time_min)}')
  113. if int(rule_duration_max) >= int(float(video_dict["duration"])) >= int(rule_duration_min) \
  114. and int(rule_play_cnt_max) >= int(video_dict['play_cnt']) >= int(rule_play_cnt_min) \
  115. and int(time.time()) - int(video_dict["publish_time_stamp"]) <= 3600 * 24 * int(rule_period_min) \
  116. and int(rule_like_cnt_max) >= int(video_dict['like_cnt']) >= int(rule_like_cnt_min) \
  117. and int(rule_comment_cnt_max) >= int(video_dict['comment_cnt']) >= int(rule_comment_cnt_min) \
  118. and int(rule_share_cnt_max) >= int(video_dict['share_cnt']) >= int(rule_share_cnt_min) \
  119. and int(rule_width_max) >= int(video_dict['video_width']) >= int(rule_width_min) \
  120. and int(rule_height_max) >= int(video_dict['video_height']) >= int(rule_height_min) \
  121. and int(rule_publish_time_max) >= int(video_dict['publish_time_stamp']) >= int(rule_publish_time_min):
  122. return True
  123. else:
  124. return False
  125. @classmethod
  126. def repeat_video(cls, log_type, crawler, video_id, env):
  127. sql = f""" select * from crawler_video where platform="小年糕" and out_video_id="{video_id}"; """
  128. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  129. return len(repeat_video)
  130. @classmethod
  131. def repeat_hour(cls, log_type, crawler, video_id, env):
  132. sql = f""" select * from crawler_xiaoniangao_hour where platform="小年糕" and out_video_id="{video_id}"; """
  133. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  134. return len(repeat_video)
  135. # 获取列表
  136. @classmethod
  137. def get_videoList(cls, log_type, crawler, rule_dict, env):
  138. uid_token_dict = cls.uid_token_dict
  139. url = "https://kapi.xiaoniangao.cn/trends/get_recommend_trends"
  140. headers = {
  141. "x-b3-traceid": '1c403a4aa72e3c',
  142. "X-Token-Id": 'ab619e96d801f1567388629260aa68ec-1202200806',
  143. "uid": uid_token_dict['uid'],
  144. "content-type": "application/json",
  145. "Accept-Encoding": "gzip,compress,br,deflate",
  146. "User-Agent": 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)'
  147. ' AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 '
  148. 'MicroMessenger/8.0.20(0x18001432) NetType/WIFI Language/zh_CN',
  149. "Referer": 'https://servicewechat.com/wxd7911e4c177690e4/624/page-frame.html'
  150. }
  151. data = {
  152. "log_params": {
  153. "page": "discover_rec",
  154. "common": {
  155. "brand": "iPhone",
  156. "device": "iPhone 11",
  157. "os": "iOS 14.7.1",
  158. "weixinver": "8.0.20",
  159. "srcver": "2.24.2",
  160. "net": "wifi",
  161. "scene": 1089
  162. }
  163. },
  164. "qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!750x500r/crop/750x500/interlace/1/format/jpg",
  165. "h_qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!80x80r/crop/80x80/interlace/1/format/jpg",
  166. "share_width": 625,
  167. "share_height": 500,
  168. "ext": {
  169. "fmid": 0,
  170. "items": {}
  171. },
  172. "app": "xng",
  173. "rec_scene": "discover_rec",
  174. "log_common_params": {
  175. "e": [{
  176. "data": {
  177. "page": "discoverIndexPage",
  178. "topic": "recommend"
  179. },
  180. "ab": {}
  181. }],
  182. "ext": {
  183. "brand": "iPhone",
  184. "device": "iPhone 11",
  185. "os": "iOS 14.7.1",
  186. "weixinver": "8.0.20",
  187. "srcver": "2.24.3",
  188. "net": "wifi",
  189. "scene": "1089"
  190. },
  191. "pj": "1",
  192. "pf": "2",
  193. "session_id": "7bcce313-b57d-4305-8d14-6ebd9a1bad29"
  194. },
  195. "refresh": False,
  196. "token": uid_token_dict["token"],
  197. "uid": uid_token_dict["uid"],
  198. "proj": "ma",
  199. "wx_ver": "8.0.20",
  200. "code_ver": "3.62.0"
  201. }
  202. urllib3.disable_warnings()
  203. r = requests.post(url=url, headers=headers, json=data, proxies=proxies, verify=False)
  204. if 'data' not in r.text or r.status_code != 200:
  205. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  206. return
  207. elif "data" not in r.json():
  208. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()}\n")
  209. return
  210. elif "list" not in r.json()["data"]:
  211. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']}\n")
  212. return
  213. elif len(r.json()['data']['list']) == 0:
  214. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']['list']}\n")
  215. return
  216. else:
  217. # 视频列表数据
  218. feeds = r.json()["data"]["list"]
  219. for i in range(len(feeds)):
  220. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  221. xiaoniangao_title = feeds[i].get("title", "").strip().replace("\n", "") \
  222. .replace("/", "").replace("\r", "").replace("#", "") \
  223. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  224. .replace(":", "").replace("*", "").replace("?", "") \
  225. .replace("?", "").replace('"', "").replace("<", "") \
  226. .replace(">", "").replace("|", "").replace(" ", "")\
  227. .replace('"', '').replace("'", '')
  228. # 随机取一个表情/符号
  229. emoji = random.choice(get_config_from_mysql(log_type, crawler, env, "emoji"))
  230. # 生成最终标题,标题list[表情+title, title+表情]随机取一个
  231. video_title = random.choice([f"{emoji}{xiaoniangao_title}", f"{xiaoniangao_title}{emoji}"])
  232. # 视频 ID
  233. video_id = feeds[i].get("vid", "")
  234. # 播放量
  235. play_cnt = feeds[i].get("play_pv", 0)
  236. # 点赞量
  237. like_cnt = feeds[i].get("favor", {}).get("total", 0)
  238. # 评论数
  239. comment_cnt = feeds[i].get("comment_count", 0)
  240. # 分享量
  241. share_cnt = feeds[i].get("share", 0)
  242. # 时长
  243. duration = int(feeds[i].get("du", 0)/1000)
  244. # 宽和高
  245. video_width = int(feeds[i].get("w", 0))
  246. video_height = int(feeds[i].get("h", 0))
  247. # 发布时间
  248. publish_time_stamp = int(int(feeds[i].get("t", 0))/1000)
  249. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  250. # 用户名 / 头像
  251. user_name = feeds[i].get("user", {}).get("nick", "").strip().replace("\n", "") \
  252. .replace("/", "").replace("快手", "").replace(" ", "") \
  253. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  254. avatar_url = feeds[i].get("user", {}).get("hurl", "")
  255. # 用户 ID
  256. profile_id = feeds[i]["id"]
  257. # 用户 mid
  258. profile_mid = feeds[i]["user"]["mid"]
  259. # 视频封面
  260. cover_url = feeds[i].get("url", "")
  261. # 视频播放地址
  262. video_url = feeds[i].get("v_url", "")
  263. video_dict = {
  264. "video_title": video_title,
  265. "video_id": video_id,
  266. "duration": duration,
  267. "play_cnt": play_cnt,
  268. "like_cnt": like_cnt,
  269. "comment_cnt": comment_cnt,
  270. "share_cnt": share_cnt,
  271. "user_name": user_name,
  272. "publish_time_stamp": publish_time_stamp,
  273. "publish_time_str": publish_time_str,
  274. "video_width": video_width,
  275. "video_height": video_height,
  276. "avatar_url": avatar_url,
  277. "profile_id": profile_id,
  278. "profile_mid": profile_mid,
  279. "cover_url": cover_url,
  280. "video_url": video_url,
  281. "session": f"xiaoniangao-hour-{int(time.time())}"
  282. }
  283. for k, v in video_dict.items():
  284. Common.logger(log_type, crawler).info(f"{k}:{v}")
  285. # 过滤无效视频
  286. if video_title == "" or video_id == "" or video_url == "":
  287. Common.logger(log_type, crawler).warning("无效视频\n")
  288. # 抓取基础规则过滤
  289. elif cls.download_rule(log_type, crawler, video_dict, rule_dict) is False:
  290. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  291. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  292. Common.logger(log_type, crawler).info('视频已下载\n')
  293. # 过滤敏感词
  294. elif any(str(word) if str(word) in video_title else False for word in get_config_from_mysql(log_type, crawler, env, "filter", action="")) is True:
  295. Common.logger(log_type, crawler).info("视频已中过滤词\n")
  296. else:
  297. # 写入飞书小时级feeds数据库表
  298. insert_sql = f""" insert into crawler_xiaoniangao_hour(profile_id,
  299. profile_mid,
  300. platform,
  301. out_video_id,
  302. video_title,
  303. user_name,
  304. cover_url,
  305. video_url,
  306. duration,
  307. publish_time,
  308. play_cnt,
  309. crawler_time_stamp,
  310. crawler_time)
  311. values({profile_id},
  312. {profile_mid},
  313. "{cls.platform}",
  314. "{video_id}",
  315. "{video_title}",
  316. "{user_name}",
  317. "{cover_url}",
  318. "{video_url}",
  319. {duration},
  320. "{publish_time_str}",
  321. {play_cnt},
  322. {int(time.time())},
  323. "{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))}"
  324. )"""
  325. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  326. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  327. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  328. @classmethod
  329. def get_video_info(cls, log_type, crawler, p_id, p_mid, v_title, v_id):
  330. uid_token_dict = cls.uid_token_dict
  331. url = "https://kapi.xiaoniangao.cn/profile/get_profile_by_id"
  332. headers = {
  333. "x-b3-traceid": '1c403a4aa72e3c',
  334. "X-Token-Id": 'ab619e96d801f1567388629260aa68ec-1202200806',
  335. "uid": uid_token_dict['uid'],
  336. "content-type": "application/json",
  337. "Accept-Encoding": "gzip,compress,br,deflate",
  338. "User-Agent": 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)'
  339. ' AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 '
  340. 'MicroMessenger/8.0.20(0x18001432) NetType/WIFI Language/zh_CN',
  341. "Referer": 'https://servicewechat.com/wxd7911e4c177690e4/624/page-frame.html'
  342. }
  343. data = {
  344. "play_src": "1",
  345. "profile_id": int(p_id),
  346. "profile_mid": int(p_mid),
  347. "qs": "imageMogr2/gravity/center/rotate/$/thumbnail/"
  348. "!400x400r/crop/400x400/interlace/1/format/jpg",
  349. "h_qs": "imageMogr2/gravity/center/rotate/$/thumbnail"
  350. "/!80x80r/crop/80x80/interlace/1/format/jpg",
  351. "share_width": 625,
  352. "share_height": 500,
  353. "no_comments": True,
  354. "no_follow": True,
  355. "vid": v_id,
  356. "hot_l1_comment": True,
  357. "token": uid_token_dict['token'],
  358. "uid": uid_token_dict['uid'],
  359. "proj": "ma",
  360. "wx_ver": "8.0.20",
  361. "code_ver": "3.62.0",
  362. "log_common_params": {
  363. "e": [{
  364. "data": {
  365. "page": "dynamicSharePage"
  366. }
  367. }],
  368. "ext": {
  369. "brand": "iPhone",
  370. "device": "iPhone 11",
  371. "os": "iOS 14.7.1",
  372. "weixinver": "8.0.20",
  373. "srcver": "2.24.3",
  374. "net": "wifi",
  375. "scene": "1089"
  376. },
  377. "pj": "1",
  378. "pf": "2",
  379. "session_id": "7bcce313-b57d-4305-8d14-6ebd9a1bad29"
  380. }
  381. }
  382. urllib3.disable_warnings()
  383. r = requests.post(headers=headers, url=url, json=data, proxies=proxies, verify=False)
  384. if r.status_code != 200 or 'data' not in r.text:
  385. Common.logger(log_type, crawler).warning(f"get_videoInfo:{r.text}\n")
  386. else:
  387. hour_play_cnt = r.json()["data"]["play_pv"]
  388. hour_cover_url = r.json()["data"]["url"]
  389. hour_video_url = r.json()["data"]["v_url"]
  390. hour_video_duration = r.json()["data"]["du"]
  391. hour_video_comment_cnt = r.json()["data"]["comment_count"]
  392. hour_video_like_cnt = r.json()["data"]["favor"]["total"]
  393. hour_video_share_cnt = r.json()["data"]["share"]
  394. hour_video_width = r.json()["data"]["w"]
  395. hour_video_height = r.json()["data"]["h"]
  396. hour_video_send_time = r.json()["data"]["t"]
  397. publish_time_stamp = int(int(hour_video_send_time) / 1000)
  398. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  399. hour_user_name = r.json()["data"]["user"]["nick"]
  400. hour_head_url = r.json()["data"]["user"]["hurl"]
  401. video_info_dict = {
  402. "video_id": v_id,
  403. "video_title": v_title,
  404. "duration": hour_video_duration,
  405. "play_cnt": hour_play_cnt,
  406. "like_cnt": hour_video_like_cnt,
  407. "comment_cnt": hour_video_comment_cnt,
  408. "share_cnt": hour_video_share_cnt,
  409. "user_name": hour_user_name,
  410. "publish_time_stamp": publish_time_stamp,
  411. "publish_time_str": publish_time_str,
  412. "video_width": hour_video_width,
  413. "video_height": hour_video_height,
  414. "avatar_url": hour_head_url,
  415. "profile_id": p_id,
  416. "profile_mid": p_mid,
  417. "cover_url": hour_cover_url,
  418. "video_url": hour_video_url,
  419. "session": f"xiaoniangao-hour-{int(time.time())}"
  420. }
  421. return video_info_dict
  422. # 更新小时榜数据
  423. @classmethod
  424. def update_videoList(cls, log_type, crawler, rule_dict, strategy, oss_endpoint, env):
  425. """
  426. 更新小时榜数据
  427. """
  428. befor_yesterday = (datetime.date.today() + datetime.timedelta(days=-3)).strftime("%Y-%m-%d %H:%M:%S")
  429. update_time_stamp = int(time.mktime(time.strptime(befor_yesterday, "%Y-%m-%d %H:%M:%S")))
  430. select_sql = f""" select * from crawler_xiaoniangao_hour where crawler_time_stamp >= {update_time_stamp} GROUP BY out_video_id """
  431. update_video_list = MysqlHelper.get_values(log_type, crawler, select_sql, env)
  432. if len(update_video_list) == 0:
  433. Common.logger(log_type, crawler).info("暂无需要更新的小时榜数据\n")
  434. return
  435. for update_video_info in update_video_list:
  436. profile_id = update_video_info["profile_id"]
  437. profile_mid = update_video_info["profile_mid"]
  438. video_title = update_video_info["video_title"]
  439. video_id = update_video_info["out_video_id"]
  440. if datetime.datetime.now().hour == 10 and datetime.datetime.now().minute <= 10:
  441. video_info_dict = cls.get_video_info(log_type=log_type,
  442. crawler=crawler,
  443. p_id=profile_id,
  444. p_mid=profile_mid,
  445. v_title=video_title,
  446. v_id=video_id)
  447. ten_play_cnt = video_info_dict['play_cnt']
  448. Common.logger(log_type, crawler).info(f"ten_play_cnt:{ten_play_cnt}")
  449. update_sql = f""" update crawler_xiaoniangao_hour set ten_play_cnt={ten_play_cnt} WHERE out_video_id="{video_id}"; """
  450. # Common.logger(log_type, crawler).info(f"update_sql:{update_sql}")
  451. MysqlHelper.update_values(log_type, crawler, update_sql, env)
  452. cls.download_publish(log_type=log_type,
  453. crawler=crawler,
  454. video_info_dict=video_info_dict,
  455. rule_dict=rule_dict,
  456. update_video_info=update_video_info,
  457. strategy=strategy,
  458. oss_endpoint=oss_endpoint,
  459. env=env)
  460. elif datetime.datetime.now().hour == 15 and datetime.datetime.now().minute <= 10:
  461. video_info_dict = cls.get_video_info(log_type=log_type,
  462. crawler=crawler,
  463. p_id=profile_id,
  464. p_mid=profile_mid,
  465. v_title=video_title,
  466. v_id=video_id)
  467. fifteen_play_cnt = video_info_dict['play_cnt']
  468. Common.logger(log_type, crawler).info(f"fifteen_play_cnt:{fifteen_play_cnt}")
  469. update_sql = f""" update crawler_xiaoniangao_hour set fifteen_play_cnt={fifteen_play_cnt} WHERE out_video_id="{video_id}"; """
  470. # Common.logger(log_type, crawler).info(f"update_sql:{update_sql}")
  471. MysqlHelper.update_values(log_type, crawler, update_sql, env)
  472. cls.download_publish(log_type=log_type,
  473. crawler=crawler,
  474. video_info_dict=video_info_dict,
  475. rule_dict=rule_dict,
  476. update_video_info=update_video_info,
  477. strategy=strategy,
  478. oss_endpoint=oss_endpoint,
  479. env=env)
  480. elif datetime.datetime.now().hour == 20 and datetime.datetime.now().minute <= 10:
  481. video_info_dict = cls.get_video_info(log_type=log_type,
  482. crawler=crawler,
  483. p_id=profile_id,
  484. p_mid=profile_mid,
  485. v_title=video_title,
  486. v_id=video_id)
  487. twenty_play_cnt = video_info_dict['play_cnt']
  488. Common.logger(log_type, crawler).info(f"twenty_play_cnt:{twenty_play_cnt}")
  489. update_sql = f""" update crawler_xiaoniangao_hour set twenty_play_cnt={twenty_play_cnt} WHERE out_video_id="{video_id}"; """
  490. # Common.logger(log_type, crawler).info(f"update_sql:{update_sql}")
  491. MysqlHelper.update_values(log_type, crawler, update_sql, env)
  492. cls.download_publish(log_type=log_type,
  493. crawler=crawler,
  494. video_info_dict=video_info_dict,
  495. rule_dict=rule_dict,
  496. update_video_info=update_video_info,
  497. strategy=strategy,
  498. oss_endpoint=oss_endpoint,
  499. env=env)
  500. else:
  501. pass
  502. @classmethod
  503. def download(cls, log_type, crawler, video_info_dict, rule_dict, strategy, oss_endpoint, env):
  504. # 下载封面
  505. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_info_dict["video_title"],
  506. url=video_info_dict["cover_url"])
  507. # 下载视频
  508. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_info_dict["video_title"],
  509. url=video_info_dict["video_url"])
  510. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  511. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_info_dict)
  512. # 上传视频
  513. Common.logger(log_type, crawler).info("开始上传视频...")
  514. our_video_id = Publish.upload_and_publish(log_type=log_type,
  515. crawler=crawler,
  516. strategy=strategy,
  517. our_uid="hour",
  518. env=env,
  519. oss_endpoint=oss_endpoint)
  520. if env == "dev":
  521. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  522. else:
  523. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  524. Common.logger(log_type, crawler).info("视频上传完成")
  525. if our_video_id is None:
  526. # 删除视频文件夹
  527. shutil.rmtree(f"./{crawler}/videos/{video_info_dict['video_title']}")
  528. return
  529. # # 视频信息保存数据库
  530. # rule_dict = {
  531. # "duration": {"min": 40},
  532. # "play_cnt": {"min": 4000},
  533. # "publish_day": {"min": 10}
  534. # }
  535. insert_sql = f""" insert into crawler_video(video_id,
  536. out_user_id,
  537. platform,
  538. strategy,
  539. out_video_id,
  540. video_title,
  541. cover_url,
  542. video_url,
  543. duration,
  544. publish_time,
  545. play_cnt,
  546. crawler_rule,
  547. width,
  548. height)
  549. values({our_video_id},
  550. "{video_info_dict['profile_id']}",
  551. "{cls.platform}",
  552. "小时榜爬虫策略",
  553. "{video_info_dict['video_id']}",
  554. "{video_info_dict['video_title']}",
  555. "{video_info_dict['cover_url']}",
  556. "{video_info_dict['video_url']}",
  557. {int(video_info_dict['duration'])},
  558. "{video_info_dict['publish_time_str']}",
  559. {int(video_info_dict['play_cnt'])},
  560. '{json.dumps(rule_dict)}',
  561. {int(video_info_dict['video_width'])},
  562. {int(video_info_dict['video_height'])}) """
  563. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  564. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  565. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  566. # 视频写入飞书
  567. Feishu.insert_columns(log_type, crawler, "yatRv2", "ROWS", 1, 2)
  568. # 视频ID工作表,首行写入数据
  569. upload_time = int(time.time())
  570. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  571. "小时级上升榜",
  572. str(video_info_dict['video_id']),
  573. str(video_info_dict['video_title']),
  574. our_video_link,
  575. video_info_dict['play_cnt'],
  576. video_info_dict['comment_cnt'],
  577. video_info_dict['like_cnt'],
  578. video_info_dict['share_cnt'],
  579. video_info_dict['duration'],
  580. f"{video_info_dict['video_width']}*{video_info_dict['video_height']}",
  581. str(video_info_dict['publish_time_str'].replace("-", "/")),
  582. str(video_info_dict['user_name']),
  583. str(video_info_dict['profile_id']),
  584. str(video_info_dict['profile_mid']),
  585. str(video_info_dict['avatar_url']),
  586. str(video_info_dict['cover_url']),
  587. str(video_info_dict['video_url'])]]
  588. time.sleep(1)
  589. Feishu.update_values(log_type, crawler, "yatRv2", "F2:Z2", values)
  590. Common.logger(log_type, crawler).info('视频信息写入飞书成功\n')
  591. # 下载/上传
  592. @classmethod
  593. def download_publish(cls, log_type, crawler, video_info_dict, rule_dict, update_video_info, strategy, oss_endpoint, env):
  594. if cls.repeat_video(log_type, crawler, video_info_dict["video_id"], env) != 0:
  595. Common.logger(log_type, crawler).info('视频已下载\n')
  596. # 播放量大于 50000,直接下载
  597. elif int(video_info_dict["play_cnt"]) >= 30000:
  598. Common.logger(log_type, crawler).info(
  599. f"播放量:{video_info_dict['play_cnt']} >= 30000,满足下载规则,开始下载视频")
  600. cls.download(log_type=log_type,
  601. crawler=crawler,
  602. video_info_dict=video_info_dict,
  603. rule_dict=rule_dict,
  604. strategy=strategy,
  605. oss_endpoint=oss_endpoint,
  606. env=env)
  607. # 上升榜判断逻辑,任意时间段上升量>=5000,连续两个时间段上升量>=2000
  608. elif int(update_video_info['ten_play_cnt']) >= 3000 or int(
  609. update_video_info['fifteen_play_cnt']) >= 3000 or int(update_video_info['twenty_play_cnt']) >= 3000:
  610. Common.logger(log_type, crawler).info(
  611. f"10:00 or 15:00 or 20:00 数据上升量:{int(update_video_info['ten_play_cnt'])} or {int(update_video_info['fifteen_play_cnt'])} or {int(update_video_info['twenty_play_cnt'])} >= 3000")
  612. Common.logger(log_type, crawler).info("满足下载规则,开始下载视频")
  613. cls.download(log_type=log_type,
  614. crawler=crawler,
  615. video_info_dict=video_info_dict,
  616. rule_dict=rule_dict,
  617. strategy=strategy,
  618. oss_endpoint=oss_endpoint,
  619. env=env)
  620. elif int(update_video_info['ten_play_cnt']) >= 1000 and int(update_video_info['fifteen_play_cnt']) >= 1000:
  621. Common.logger(log_type, crawler).info(
  622. f"10:00 and 15:00 数据上升量:{int(update_video_info['ten_play_cnt'])} and {int(update_video_info['fifteen_play_cnt'])} >= 1000")
  623. Common.logger(log_type, crawler).info("满足下载规则,开始下载视频")
  624. cls.download(log_type=log_type,
  625. crawler=crawler,
  626. video_info_dict=video_info_dict,
  627. rule_dict=rule_dict,
  628. strategy=strategy,
  629. oss_endpoint=oss_endpoint,
  630. env=env)
  631. elif int(update_video_info['fifteen_play_cnt']) >= 1000 and int(update_video_info['twenty_play_cnt']) >= 1000:
  632. Common.logger(log_type, crawler).info(
  633. f"15:00 and 20:00 数据上升量:{int(update_video_info['fifteen_play_cnt'])} and {int(update_video_info['twenty_play_cnt'])} >= 1000")
  634. Common.logger(log_type, crawler).info("满足下载规则,开始下载视频")
  635. cls.download(log_type=log_type,
  636. crawler=crawler,
  637. video_info_dict=video_info_dict,
  638. rule_dict=rule_dict,
  639. strategy=strategy,
  640. oss_endpoint=oss_endpoint,
  641. env=env)
  642. elif int(update_video_info['ten_play_cnt']) >= 1000 and int(update_video_info['twenty_play_cnt']) >= 1000:
  643. Common.logger(log_type, crawler).info(
  644. f"今日10:00 / 20:00数据上升量:{int(update_video_info['ten_play_cnt'])} and {int(update_video_info['twenty_play_cnt'])} >= 1000")
  645. Common.logger(log_type, crawler).info("满足下载规则,开始下载视频")
  646. cls.download(log_type=log_type,
  647. crawler=crawler,
  648. video_info_dict=video_info_dict,
  649. rule_dict=rule_dict,
  650. strategy=strategy,
  651. oss_endpoint=oss_endpoint,
  652. env=env)
  653. else:
  654. Common.logger(log_type, crawler).info("上升量不满足下载规则")
  655. if __name__ == "__main__":
  656. print(get_config_from_mysql(log_type='hour', source='xiaoniangao', env='dev', text='filter'))
  657. # print(XiaoniangaoHour.get_uid_token())
  658. # XiaoniangaoHour.get_videoList("test", "xiaoniangao", "dev")
  659. # XiaoniangaoHour.update_videoList("test", "xiaoniangao", "小时榜爬虫策略", "out", "dev")
  660. pass