xiaoniangao_play.py 20 KB

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