xiaoniangao_play.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. elif "data" not in r.json():
  150. Common.logger(log_type, crawler).info(f"get_videoList:{r.json()}")
  151. elif "list" not in r.json()["data"]:
  152. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']}")
  153. else:
  154. # 视频列表数据
  155. feeds = r.json()["data"]["list"]
  156. for i in range(len(feeds)):
  157. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  158. if "title" in feeds[i]:
  159. befor_video_title = feeds[i]["title"].strip().replace("\n", "") \
  160. .replace("/", "").replace("\r", "").replace("#", "") \
  161. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  162. .replace(":", "").replace("*", "").replace("?", "") \
  163. .replace("?", "").replace('"', "").replace("<", "") \
  164. .replace(">", "").replace("|", "").replace(" ", "").replace("#表情", "").replace("#符号", "")
  165. expression = cls.get_expression()
  166. expression_list = expression[0]
  167. char_list = expression[1]
  168. # 随机取一个表情
  169. expression = random.choice(expression_list)
  170. # 生成标题list[表情+title, title+表情]
  171. expression_title_list = [expression + befor_video_title, befor_video_title + expression]
  172. # 从标题list中随机取一个标题
  173. title_list1 = random.choice(expression_title_list)
  174. # 生成标题:原标题+符号
  175. title_list2 = befor_video_title + random.choice(char_list)
  176. # 表情和标题组合,与标题和符号组合,汇总成待使用的标题列表
  177. title_list4 = [title_list2, title_list1]
  178. # 最终标题
  179. video_title = random.choice(title_list4)
  180. else:
  181. video_title = 0
  182. # 视频 ID
  183. if "vid" in feeds[i]:
  184. video_id = feeds[i]["vid"]
  185. else:
  186. video_id = 0
  187. # 播放量
  188. if "play_pv" in feeds[i]:
  189. video_play_cnt = feeds[i]["play_pv"]
  190. else:
  191. video_play_cnt = 0
  192. # 评论量
  193. if "comment_count" in feeds[i]:
  194. video_comment_cnt = feeds[i]["comment_count"]
  195. else:
  196. video_comment_cnt = 0
  197. # 点赞量
  198. if "favor" in feeds[i]:
  199. video_like_cnt = feeds[i]["favor"]["total"]
  200. else:
  201. video_like_cnt = 0
  202. # 分享量
  203. if "share" in feeds[i]:
  204. video_share_cnt = feeds[i]["share"]
  205. else:
  206. video_share_cnt = 0
  207. # 时长
  208. if "du" in feeds[i]:
  209. video_duration = int(feeds[i]["du"] / 1000)
  210. else:
  211. video_duration = 0
  212. # 宽和高
  213. if "w" or "h" in feeds[i]:
  214. video_width = feeds[i]["w"]
  215. video_height = feeds[i]["h"]
  216. else:
  217. video_width = 0
  218. video_height = 0
  219. # 发布时间
  220. if "t" in feeds[i]:
  221. video_send_time = feeds[i]["t"]
  222. else:
  223. video_send_time = 0
  224. publish_time_stamp = int(int(video_send_time)/1000)
  225. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  226. # 用户名 / 头像
  227. if "user" in feeds[i]:
  228. user_name = feeds[i]["user"]["nick"].strip().replace("\n", "") \
  229. .replace("/", "").replace("快手", "").replace(" ", "") \
  230. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  231. head_url = feeds[i]["user"]["hurl"]
  232. else:
  233. user_name = 0
  234. head_url = 0
  235. # 用户 ID
  236. profile_id = feeds[i]["id"]
  237. # 用户 mid
  238. profile_mid = feeds[i]["user"]["mid"]
  239. # 视频封面
  240. if "url" in feeds[i]:
  241. cover_url = feeds[i]["url"]
  242. else:
  243. cover_url = 0
  244. # 视频播放地址
  245. if "v_url" in feeds[i]:
  246. video_url = feeds[i]["v_url"]
  247. else:
  248. video_url = 0
  249. video_dict = {
  250. "video_title": video_title,
  251. "video_id": video_id,
  252. "duration": video_duration,
  253. "play_cnt": video_play_cnt,
  254. "like_cnt": video_like_cnt,
  255. "comment_cnt": video_comment_cnt,
  256. "share_cnt": video_share_cnt,
  257. "user_name": user_name,
  258. "publish_time_stamp": publish_time_stamp,
  259. "publish_time_str": publish_time_str,
  260. "video_width": video_width,
  261. "video_height": video_height,
  262. "avatar_url": head_url,
  263. "profile_id": profile_id,
  264. "profile_mid": profile_mid,
  265. "cover_url": cover_url,
  266. "video_url": video_url,
  267. "session": f"xiaoniangao-play-{int(time.time())}"
  268. }
  269. for k, v in video_dict.items():
  270. Common.logger(log_type, crawler).info(f"{k}:{v}")
  271. cls.download_publish(log_type=log_type,
  272. crawler=crawler,
  273. video_dict=video_dict,
  274. strategy=strategy,
  275. oss_endpoint=oss_endpoint,
  276. env=env)
  277. except Exception as e:
  278. Common.logger(log_type, crawler).error("get_play_feeds异常:{}", e)
  279. @classmethod
  280. def repeat_video(cls, log_type, crawler, video_id, env):
  281. sql = f""" select * from crawler_video where platform="小年糕" and out_video_id="{video_id}"; """
  282. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  283. return len(repeat_video)
  284. @classmethod
  285. def download_publish(cls, log_type, crawler, video_dict, strategy, oss_endpoint, env):
  286. # try:
  287. # 过滤无效视频
  288. if video_dict["video_id"] == 0 \
  289. or video_dict["video_url"] == 0\
  290. or video_dict["cover_url"] == 0:
  291. Common.logger(log_type, crawler).warning("无效视频\n")
  292. # 抓取规则
  293. elif cls.download_rule(video_dict) is False:
  294. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  295. # 去重
  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_dict['video_title'] else False for word in filter_word(log_type, crawler, "小年糕", env)) is True:
  300. Common.logger(log_type, crawler).info("视频已中过滤词\n")
  301. else:
  302. # 下载封面
  303. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  304. # 下载视频
  305. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  306. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  307. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  308. # 上传视频
  309. Common.logger(log_type, crawler).info("开始上传视频...")
  310. our_video_id = Publish.upload_and_publish(log_type=log_type,
  311. crawler=crawler,
  312. strategy=strategy,
  313. our_uid="play",
  314. env=env,
  315. oss_endpoint=oss_endpoint)
  316. if env == "dev":
  317. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  318. else:
  319. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  320. Common.logger(log_type, crawler).info("视频上传完成")
  321. if our_video_id is None:
  322. # 删除视频文件夹
  323. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  324. return
  325. # 视频信息保存数据库
  326. rule_dict = {
  327. "duration": {"min": 40},
  328. "play_cnt": {"min": 80000},
  329. "min_publish_day": {"min": 60}
  330. }
  331. insert_sql = f""" insert into crawler_video(video_id,
  332. out_user_id,
  333. platform,
  334. strategy,
  335. out_video_id,
  336. video_title,
  337. cover_url,
  338. video_url,
  339. duration,
  340. publish_time,
  341. play_cnt,
  342. crawler_rule,
  343. width,
  344. height)
  345. values({our_video_id},
  346. "{video_dict['profile_id']}",
  347. "{cls.platform}",
  348. "播放量榜爬虫策略",
  349. "{video_dict['video_id']}",
  350. "{video_dict['video_title']}",
  351. "{video_dict['cover_url']}",
  352. "{video_dict['video_url']}",
  353. {int(video_dict['duration'])},
  354. "{video_dict['publish_time_str']}",
  355. {int(video_dict['play_cnt'])},
  356. '{json.dumps(rule_dict)}',
  357. {int(video_dict['video_width'])},
  358. {int(video_dict['video_height'])}) """
  359. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  360. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  361. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  362. # 视频写入飞书
  363. Feishu.insert_columns(log_type, crawler, "c85k1C", "ROWS", 1, 2)
  364. # 视频ID工作表,首行写入数据
  365. upload_time = int(time.time())
  366. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  367. "播放量榜爬虫策略",
  368. str(video_dict['video_id']),
  369. str(video_dict['video_title']),
  370. our_video_link,
  371. video_dict['play_cnt'],
  372. video_dict['comment_cnt'],
  373. video_dict['like_cnt'],
  374. video_dict['share_cnt'],
  375. video_dict['duration'],
  376. f"{video_dict['video_width']}*{video_dict['video_height']}",
  377. str(video_dict['publish_time_str']),
  378. str(video_dict['user_name']),
  379. str(video_dict['profile_id']),
  380. str(video_dict['profile_mid']),
  381. str(video_dict['avatar_url']),
  382. str(video_dict['cover_url']),
  383. str(video_dict['video_url'])]]
  384. time.sleep(1)
  385. Feishu.update_values(log_type, crawler, "c85k1C", "F2:Z2", values)
  386. Common.logger(log_type, crawler).info('视频信息写入飞书成功\n')
  387. # except Exception as e:
  388. # Common.logger(log_type, crawler).error('download_publish异常:{}', e)
  389. if __name__ == '__main__':
  390. XiaoniangaoPlay.get_videoList("play", "xiaoniangao", "播放量榜爬虫策略", "out", "dev")
  391. pass