xiaoniangao_hour_scheduling.py 33 KB

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