xiaoniangao_hour_scheduling.py 35 KB

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