xiaoniangao_hour_scheduling.py 33 KB

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