xiaoniangao_play.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/3/16
  4. import json
  5. import os
  6. import random
  7. import shutil
  8. import sys
  9. import time
  10. import requests
  11. import urllib3
  12. from common.public import filter_word
  13. from common.scheduling_db import MysqlHelper
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common.feishu import Feishu
  17. from common.publish import Publish
  18. proxies = {"http": None, "https": None}
  19. class XiaoniangaoPlay:
  20. platform = "小年糕"
  21. # 生成 uid、token
  22. @classmethod
  23. def get_uid_token(cls):
  24. words = "abcdefghijklmnopqrstuvwxyz0123456789"
  25. 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))}"""
  26. token = "".join(random.sample(words, 32))
  27. uid_token_dict = {
  28. "uid": uid,
  29. "token": token
  30. }
  31. return uid_token_dict
  32. # 基础门槛规则
  33. @classmethod
  34. def download_rule(cls, video_dict):
  35. """
  36. 下载视频的基本规则
  37. :param video_dict: 视频信息,字典格式
  38. :return: 满足规则,返回 True;反之,返回 False
  39. """
  40. # 视频时长
  41. if int(float(video_dict['duration'])) >= 40:
  42. # 宽或高
  43. if int(video_dict['video_width']) >= 0 or int(video_dict['video_height']) >= 0:
  44. # 播放量
  45. if int(video_dict['play_cnt']) >= 80000:
  46. # 点赞量
  47. if int(video_dict['like_cnt']) >= 0:
  48. # 分享量
  49. if int(video_dict['share_cnt']) >= 0:
  50. # 发布时间 <= 60 天
  51. if int(time.time()) - int(video_dict['publish_time_stamp']) <= 3600 * 24 * 60:
  52. return True
  53. else:
  54. return False
  55. else:
  56. return False
  57. else:
  58. return False
  59. else:
  60. return False
  61. return False
  62. return False
  63. # 获取表情及符号
  64. @classmethod
  65. def get_expression(cls):
  66. # 表情列表
  67. expression_list = ['📍', '⭕️', '🔥', '📣', '🎈', '⚡', '🔔', '🚩', '💢', '💎', '👉', '💓', '❗️', '🔴', '🔺', '♦️', '♥️', '👉', '👈', '🏆', '❤️\u200d🔥']
  68. # 符号列表
  69. char_list = ['...', '~~']
  70. return expression_list, char_list
  71. # 获取列表
  72. @classmethod
  73. def get_videoList(cls, log_type, crawler, strategy, oss_endpoint, env):
  74. uid_token_dict = cls.get_uid_token()
  75. url = "https://kapi.xiaoniangao.cn/trends/get_recommend_trends"
  76. headers = {
  77. # "x-b3-traceid": cls.play_x_b3_traceid,
  78. "x-b3-traceid": '1dc0a6d0929a2b',
  79. # "X-Token-Id": cls.play_x_token_id,
  80. "X-Token-Id": 'ae99a4953804085ebb0ae36fa138031d-1146052582',
  81. # "uid": cls.play_uid,
  82. "uid": uid_token_dict['uid'],
  83. "content-type": "application/json",
  84. "Accept-Encoding": "gzip,compress,br,deflate",
  85. "User-Agent": 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)'
  86. ' AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 '
  87. 'MicroMessenger/8.0.20(0x18001432) NetType/WIFI Language/zh_CN',
  88. # "Referer": cls.play_referer
  89. "Referer": 'https://servicewechat.com/wxd7911e4c177690e4/620/page-frame.html'
  90. }
  91. data = {
  92. "log_params": {
  93. "page": "discover_rec",
  94. "common": {
  95. "brand": "iPhone",
  96. "device": "iPhone 11",
  97. "os": "iOS 14.7.1",
  98. "weixinver": "8.0.20",
  99. "srcver": "2.24.2",
  100. "net": "wifi",
  101. "scene": 1089
  102. }
  103. },
  104. "qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!750x500r/crop/750x500/interlace/1/format/jpg",
  105. "h_qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!80x80r/crop/80x80/interlace/1/format/jpg",
  106. "share_width": 625,
  107. "share_height": 500,
  108. "ext": {
  109. "fmid": 0,
  110. "items": {}
  111. },
  112. "app": "xng",
  113. "rec_scene": "discover_rec",
  114. "log_common_params": {
  115. "e": [{
  116. "data": {
  117. "page": "discoverIndexPage",
  118. "topic": "recommend"
  119. },
  120. "ab": {}
  121. }],
  122. "ext": {
  123. "brand": "iPhone",
  124. "device": "iPhone 11",
  125. "os": "iOS 14.7.1",
  126. "weixinver": "8.0.20",
  127. "srcver": "2.24.3",
  128. "net": "wifi",
  129. "scene": "1089"
  130. },
  131. "pj": "1",
  132. "pf": "2",
  133. "session_id": "7bcce313-b57d-4305-8d14-6ebd9a1bad29"
  134. },
  135. "refresh": False,
  136. # "token": cls.play_token,
  137. "token": uid_token_dict['token'],
  138. # "uid": cls.play_uid,
  139. "uid": uid_token_dict['uid'],
  140. "proj": "ma",
  141. "wx_ver": "8.0.20",
  142. "code_ver": "3.62.0"
  143. }
  144. # try:
  145. urllib3.disable_warnings()
  146. r = requests.post(url=url, headers=headers, json=data, proxies=proxies, verify=False)
  147. if "data" not in r.text or r.status_code != 200:
  148. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}")
  149. return
  150. elif "data" not in r.json():
  151. Common.logger(log_type, crawler).info(f"get_videoList:{r.json()}")
  152. return
  153. elif "list" not in r.json()["data"]:
  154. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']}")
  155. return
  156. elif len(r.json()["data"]["list"]) == 0:
  157. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']['list']}")
  158. return
  159. else:
  160. # 视频列表数据
  161. feeds = r.json()["data"]["list"]
  162. for i in range(len(feeds)):
  163. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  164. if "title" in feeds[i]:
  165. befor_video_title = feeds[i]["title"].strip().replace("\n", "") \
  166. .replace("/", "").replace("\r", "").replace("#", "") \
  167. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  168. .replace(":", "").replace("*", "").replace("?", "") \
  169. .replace("?", "").replace('"', "").replace("<", "") \
  170. .replace(">", "").replace("|", "").replace(" ", "").replace("#表情", "").replace("#符号", "").replace('"' ,'').replace("'", '')
  171. expression = cls.get_expression()
  172. expression_list = expression[0]
  173. char_list = expression[1]
  174. # 随机取一个表情
  175. expression = random.choice(expression_list)
  176. # 生成标题list[表情+title, title+表情]
  177. expression_title_list = [expression + befor_video_title, befor_video_title + expression]
  178. # 从标题list中随机取一个标题
  179. title_list1 = random.choice(expression_title_list)
  180. # 生成标题:原标题+符号
  181. title_list2 = befor_video_title + random.choice(char_list)
  182. # 表情和标题组合,与标题和符号组合,汇总成待使用的标题列表
  183. title_list4 = [title_list2, title_list1]
  184. # 最终标题
  185. video_title = random.choice(title_list4)
  186. else:
  187. video_title = 0
  188. # 视频 ID
  189. if "vid" in feeds[i]:
  190. video_id = feeds[i]["vid"]
  191. else:
  192. video_id = 0
  193. # 播放量
  194. if "play_pv" in feeds[i]:
  195. video_play_cnt = feeds[i]["play_pv"]
  196. else:
  197. video_play_cnt = 0
  198. # 评论量
  199. if "comment_count" in feeds[i]:
  200. video_comment_cnt = feeds[i]["comment_count"]
  201. else:
  202. video_comment_cnt = 0
  203. # 点赞量
  204. if "favor" in feeds[i]:
  205. video_like_cnt = feeds[i]["favor"]["total"]
  206. else:
  207. video_like_cnt = 0
  208. # 分享量
  209. if "share" in feeds[i]:
  210. video_share_cnt = feeds[i]["share"]
  211. else:
  212. video_share_cnt = 0
  213. # 时长
  214. if "du" in feeds[i]:
  215. video_duration = int(feeds[i]["du"] / 1000)
  216. else:
  217. video_duration = 0
  218. # 宽和高
  219. if "w" or "h" in feeds[i]:
  220. video_width = feeds[i]["w"]
  221. video_height = feeds[i]["h"]
  222. else:
  223. video_width = 0
  224. video_height = 0
  225. # 发布时间
  226. if "t" in feeds[i]:
  227. video_send_time = feeds[i]["t"]
  228. else:
  229. video_send_time = 0
  230. publish_time_stamp = int(int(video_send_time)/1000)
  231. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  232. # 用户名 / 头像
  233. if "user" in feeds[i]:
  234. user_name = feeds[i]["user"]["nick"].strip().replace("\n", "") \
  235. .replace("/", "").replace("快手", "").replace(" ", "") \
  236. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  237. head_url = feeds[i]["user"]["hurl"]
  238. else:
  239. user_name = 0
  240. head_url = 0
  241. # 用户 ID
  242. profile_id = feeds[i]["id"]
  243. # 用户 mid
  244. profile_mid = feeds[i]["user"]["mid"]
  245. # 视频封面
  246. if "url" in feeds[i]:
  247. cover_url = feeds[i]["url"]
  248. else:
  249. cover_url = 0
  250. # 视频播放地址
  251. if "v_url" in feeds[i]:
  252. video_url = feeds[i]["v_url"]
  253. else:
  254. video_url = 0
  255. video_dict = {
  256. "video_title": video_title,
  257. "video_id": video_id,
  258. "duration": video_duration,
  259. "play_cnt": video_play_cnt,
  260. "like_cnt": video_like_cnt,
  261. "comment_cnt": video_comment_cnt,
  262. "share_cnt": video_share_cnt,
  263. "user_name": user_name,
  264. "publish_time_stamp": publish_time_stamp,
  265. "publish_time_str": publish_time_str,
  266. "video_width": video_width,
  267. "video_height": video_height,
  268. "avatar_url": head_url,
  269. "profile_id": profile_id,
  270. "profile_mid": profile_mid,
  271. "cover_url": cover_url,
  272. "video_url": video_url,
  273. "session": f"xiaoniangao-play-{int(time.time())}"
  274. }
  275. for k, v in video_dict.items():
  276. Common.logger(log_type, crawler).info(f"{k}:{v}")
  277. cls.download_publish(log_type=log_type,
  278. crawler=crawler,
  279. video_dict=video_dict,
  280. strategy=strategy,
  281. oss_endpoint=oss_endpoint,
  282. env=env)
  283. # except Exception as e:
  284. # Common.logger(log_type, crawler).error("get_play_feeds异常:{}", e)
  285. @classmethod
  286. def repeat_video(cls, log_type, crawler, video_id, env):
  287. sql = f""" select * from crawler_video where platform="小年糕" and out_video_id="{video_id}"; """
  288. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  289. return len(repeat_video)
  290. @classmethod
  291. def download_publish(cls, log_type, crawler, video_dict, strategy, oss_endpoint, env):
  292. # try:
  293. # 过滤无效视频
  294. if video_dict["video_id"] == 0 \
  295. or video_dict["video_url"] == 0\
  296. or video_dict["cover_url"] == 0:
  297. Common.logger(log_type, crawler).warning("无效视频\n")
  298. # 抓取规则
  299. elif cls.download_rule(video_dict) is False:
  300. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  301. # 去重
  302. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  303. Common.logger(log_type, crawler).info("视频已下载\n")
  304. # 过滤词库
  305. elif any(str(word) if str(word) in video_dict['video_title'] else False for word in filter_word(log_type, crawler, "小年糕", env)) is True:
  306. Common.logger(log_type, crawler).info("视频已中过滤词\n")
  307. else:
  308. # 下载封面
  309. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  310. # 下载视频
  311. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  312. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  313. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  314. # 上传视频
  315. Common.logger(log_type, crawler).info("开始上传视频...")
  316. our_video_id = Publish.upload_and_publish(log_type=log_type,
  317. crawler=crawler,
  318. strategy=strategy,
  319. our_uid="play",
  320. env=env,
  321. oss_endpoint=oss_endpoint)
  322. if env == "dev":
  323. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  324. else:
  325. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  326. Common.logger(log_type, crawler).info("视频上传完成")
  327. if our_video_id is None:
  328. # 删除视频文件夹
  329. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  330. return
  331. # 视频信息保存数据库
  332. rule_dict = {
  333. "duration": {"min": 40},
  334. "play_cnt": {"min": 80000},
  335. "min_publish_day": {"min": 60}
  336. }
  337. insert_sql = f""" insert into crawler_video(video_id,
  338. out_user_id,
  339. platform,
  340. strategy,
  341. out_video_id,
  342. video_title,
  343. cover_url,
  344. video_url,
  345. duration,
  346. publish_time,
  347. play_cnt,
  348. crawler_rule,
  349. width,
  350. height)
  351. values({our_video_id},
  352. "{video_dict['profile_id']}",
  353. "{cls.platform}",
  354. "播放量榜爬虫策略",
  355. "{video_dict['video_id']}",
  356. "{video_dict['video_title']}",
  357. "{video_dict['cover_url']}",
  358. "{video_dict['video_url']}",
  359. {int(video_dict['duration'])},
  360. "{video_dict['publish_time_str']}",
  361. {int(video_dict['play_cnt'])},
  362. '{json.dumps(rule_dict)}',
  363. {int(video_dict['video_width'])},
  364. {int(video_dict['video_height'])}) """
  365. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  366. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  367. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  368. # 视频写入飞书
  369. Feishu.insert_columns(log_type, crawler, "c85k1C", "ROWS", 1, 2)
  370. # 视频ID工作表,首行写入数据
  371. upload_time = int(time.time())
  372. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  373. "播放量榜爬虫策略",
  374. str(video_dict['video_id']),
  375. str(video_dict['video_title']),
  376. our_video_link,
  377. video_dict['play_cnt'],
  378. video_dict['comment_cnt'],
  379. video_dict['like_cnt'],
  380. video_dict['share_cnt'],
  381. video_dict['duration'],
  382. f"{video_dict['video_width']}*{video_dict['video_height']}",
  383. str(video_dict['publish_time_str']),
  384. str(video_dict['user_name']),
  385. str(video_dict['profile_id']),
  386. str(video_dict['profile_mid']),
  387. str(video_dict['avatar_url']),
  388. str(video_dict['cover_url']),
  389. str(video_dict['video_url'])]]
  390. time.sleep(1)
  391. Feishu.update_values(log_type, crawler, "c85k1C", "F2:Z2", values)
  392. Common.logger(log_type, crawler).info('视频信息写入飞书成功\n')
  393. # except Exception as e:
  394. # Common.logger(log_type, crawler).error('download_publish异常:{}', e)
  395. if __name__ == '__main__':
  396. XiaoniangaoPlay.get_videoList("play", "xiaoniangao", "播放量榜爬虫策略", "out", "dev")
  397. pass