recommend.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/4/8
  4. import json
  5. import os
  6. import random
  7. import sys
  8. import time
  9. import requests
  10. import urllib3
  11. sys.path.append(os.getcwd())
  12. from main.common import Common
  13. from main.feishu_lib import Feishu
  14. from main.publish import Publish
  15. proxies = {"http": None, "https": None}
  16. class Recommend:
  17. # 配置微信号
  18. wechat_sheet = Feishu.get_values_batch('recommend', 'weishi', '9fTK1f')
  19. Referer = wechat_sheet[2][2]
  20. wesee_openid = wechat_sheet[3][2]
  21. wesee_openkey = wechat_sheet[4][2]
  22. wesee_personid = wechat_sheet[5][2]
  23. wesee_access_token = wechat_sheet[6][2]
  24. wesee_thr_appid = wechat_sheet[7][2]
  25. # 已抓取视频数
  26. video_count = []
  27. crawler_count = 50
  28. # 标题过滤词库
  29. @classmethod
  30. def video_title_sensitive_words(cls, log_type):
  31. # 敏感词库列表
  32. word_list = []
  33. # 从云文档读取所有敏感词,添加到词库列表
  34. lists = Feishu.get_values_batch(log_type, 'weishi', "2Oxf8C")
  35. for a in lists:
  36. for j in a:
  37. # 过滤空的单元格内容
  38. if j is None:
  39. pass
  40. else:
  41. word_list.append(j)
  42. return word_list
  43. # 用户名过滤词库
  44. @classmethod
  45. def username_sensitive_words(cls, log_type):
  46. # 敏感词库列表
  47. word_list = []
  48. # 从云文档读取所有敏感词,添加到词库列表
  49. lists = Feishu.get_values_batch(log_type, 'weishi', "KnVAc2")
  50. for a in lists:
  51. for j in a:
  52. # 过滤空的单元格内容
  53. if j is None:
  54. pass
  55. else:
  56. word_list.append(j)
  57. return word_list
  58. # 抓取基础规则
  59. @staticmethod
  60. def download_rule(duration, width, height, like_cnt):
  61. """
  62. 下载视频的基本规则
  63. :param duration: 时长
  64. :param width: 宽
  65. :param height: 高
  66. :param like_cnt: 点赞量
  67. :return: 满足规则,返回 True;反之,返回 False
  68. """
  69. if int(float(duration)) >= 60:
  70. if int(width) >= 720 or int(height) >= 720:
  71. if int(like_cnt) >= 1000:
  72. return True
  73. else:
  74. return False
  75. return False
  76. return False
  77. # 抓取列表
  78. @classmethod
  79. def get_feeds(cls, log_type):
  80. """
  81. 1.从微视小程序首页推荐,获取视频列表
  82. 2.先在 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=caa3fa 中去重
  83. 3.再从 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr 中去重
  84. 4.添加视频信息至 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr
  85. """
  86. url = "https://api.weishi.qq.com/trpc.weishi.weishi_h5_proxy.weishi_h5_proxy/WxminiGetFeedList"
  87. headers = {
  88. "content-type": "application/json",
  89. "Accept-Encoding": "gzip,compress,br,deflate",
  90. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)"
  91. " AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
  92. " MicroMessenger/8.0.20(0x18001442) NetType/WIFI Language/zh_CN",
  93. "Referer": str(cls.Referer)
  94. }
  95. cookies = {
  96. "wesee_authtype": "3",
  97. "wesee_openid": str(cls.wesee_openid),
  98. "wesee_openkey": str(cls.wesee_openkey),
  99. "wesee_personid": str(cls.wesee_personid),
  100. "wesee_refresh_token": "",
  101. "wesee_access_token": str(cls.wesee_access_token),
  102. "wesee_thr_appid": str(cls.wesee_thr_appid),
  103. "wesee_ichid": "8"
  104. }
  105. json_data = {
  106. "req_body": {
  107. "requestType": 16,
  108. "isrefresh": 1,
  109. "isfirst": 1,
  110. "attachInfo": "",
  111. "scene_id": 22,
  112. "requestExt": {
  113. "mini_openid": str(cls.wesee_openid),
  114. "notLogin-personid": str(cls.wesee_personid)
  115. }
  116. },
  117. "req_header": {
  118. "mapExt": "{\"imageSize\":\"480\",\"adaptScene\":\"PicHDWebpLimitScene\"}"
  119. }
  120. }
  121. try:
  122. while True:
  123. urllib3.disable_warnings()
  124. r = requests.post(headers=headers, url=url, cookies=cookies, json=json_data, proxies=proxies,
  125. verify=False)
  126. response = json.loads(r.content.decode("utf8"))
  127. feeds = response["rsp_body"]["feeds"]
  128. for i in range(len(feeds)):
  129. # 视频标题过滤话题及处理特殊字符
  130. weishi_title = feeds[i]["desc"]
  131. title_split1 = weishi_title.split(" #")
  132. if title_split1[0] != "":
  133. title1 = title_split1[0]
  134. else:
  135. title1 = title_split1[-1]
  136. title_split2 = title1.split(" #")
  137. if title_split2[0] != "":
  138. title2 = title_split2[0]
  139. else:
  140. title2 = title_split2[-1]
  141. title_split3 = title2.split("@")
  142. if title_split3[0] != "":
  143. title3 = title_split3[0]
  144. else:
  145. title3 = title_split3[-1]
  146. # 视频标题
  147. video_title = title3.strip().replace("\n", "").replace("/", "")\
  148. .replace("快手", "").replace(" ", "").replace(" ", "").replace("&NBSP", "")\
  149. .replace("\r", "").replace("#", "").replace(".", "。").replace("\\", "").replace(":", "")\
  150. .replace("*", "").replace("?", "").replace("?", "").replace('"', "").replace("<", "")\
  151. .replace(">", "").replace("|", "").replace("微视", "")[:40]
  152. # 视频 ID
  153. if "id" not in feeds[i]["video"]:
  154. video_id = 0
  155. else:
  156. video_id = feeds[i]["video"]["id"]
  157. # 播放数
  158. if "playNum" not in feeds[i]["ugcData"]:
  159. video_play_cnt = 0
  160. else:
  161. video_play_cnt = feeds[i]["ugcData"]["playNum"]
  162. # 点赞数
  163. if "dingCount" not in feeds[i]["ugcData"]:
  164. video_like_cnt = 0
  165. else:
  166. video_like_cnt = feeds[i]["ugcData"]["dingCount"]
  167. # 分享数
  168. if "shareNum" not in feeds[i]["ugcData"]:
  169. video_share_cnt = 0
  170. else:
  171. video_share_cnt = feeds[i]["ugcData"]["shareNum"]
  172. # 评论数
  173. if "totalCommentNum" not in feeds[i]["ugcData"]:
  174. video_comment_cnt = 0
  175. else:
  176. video_comment_cnt = feeds[i]["ugcData"]["totalCommentNum"]
  177. # 视频时长
  178. if "duration" not in feeds[i]["video"]:
  179. video_duration = 0
  180. else:
  181. video_duration = int(int(feeds[i]["video"]["duration"]) / 1000)
  182. # 视频宽高
  183. if "width" not in feeds[i]["video"] or "height" not in feeds[i]["video"]:
  184. video_width = 0
  185. video_height = 0
  186. video_resolution = str(video_width) + "*" + str(video_height)
  187. else:
  188. video_width = feeds[i]["video"]["width"]
  189. video_height = feeds[i]["video"]["height"]
  190. video_resolution = str(video_width) + "*" + str(video_height)
  191. # 视频发布时间
  192. if "createTime" not in feeds[i]:
  193. video_send_time = 0
  194. else:
  195. video_send_time = int(feeds[i]["createTime"]) * 1000
  196. # 用户昵称
  197. user_name = feeds[i]["poster"]["nick"].strip().replace("\n", "") \
  198. .replace("/", "").replace("快手", "").replace(" ", "") \
  199. .replace(" ", "").replace("&NBSP", "").replace("\r", "").replace("微视", "")
  200. # 用户 ID
  201. user_id = feeds[i]["poster"]["id"]
  202. # 用户头像地址
  203. if "thumbURL" not in feeds[i]["material"] and "avatar" not in feeds[i]["poster"]:
  204. head_url = 0
  205. elif "thumbURL" in feeds[i]["material"]:
  206. head_url = feeds[i]["material"]["thumbURL"]
  207. else:
  208. head_url = feeds[i]["poster"]["avatar"]
  209. # 视频封面地址
  210. if len(feeds[i]["images"]) == 0:
  211. cover_url = 0
  212. else:
  213. cover_url = feeds[i]["images"][0]["url"]
  214. # 视频播放地址
  215. if "url" not in feeds[i]["video"]:
  216. video_url = 0
  217. else:
  218. video_url = feeds[i]["video"]["url"]
  219. Common.logger(log_type).info("video_title:{}".format(video_title))
  220. Common.logger(log_type).info("video_id:{}".format(video_id))
  221. Common.logger(log_type).info("video_like_cnt:{}".format(video_like_cnt))
  222. Common.logger(log_type).info("video_share_cnt:{}".format(video_share_cnt))
  223. Common.logger(log_type).info("video_comment_cnt:{}".format(video_comment_cnt))
  224. Common.logger(log_type).info("video_duration:{}秒".format(video_duration))
  225. Common.logger(log_type).info(
  226. "video_send_time:{}".format(time.strftime(
  227. "%Y/%m/%d %H:%M:%S", time.localtime(int(video_send_time) / 1000))))
  228. Common.logger(log_type).info("user_name:{}".format(user_name))
  229. Common.logger(log_type).info("video_url:{}".format(video_url))
  230. # Common.logger(log_type).info("video_play_cnt:{}".format(video_play_cnt))
  231. # Common.logger(log_type).info("video_resolution:{}".format(video_resolution))
  232. # Common.logger(log_type).info("user_id:{}".format(user_id))
  233. # Common.logger(log_type).info("head_url:{}".format(head_url))
  234. # Common.logger(log_type).info("cover_url:{}".format(cover_url))
  235. # 过滤无效视频
  236. if video_id == 0 or video_duration == 0 or video_send_time == 0 or head_url == 0 \
  237. or cover_url == 0 or video_url == 0:
  238. Common.logger(log_type).info("无效视频\n")
  239. # 判断基础规则
  240. elif cls.download_rule(video_duration, video_width, video_height, video_like_cnt) is False:
  241. Common.logger(log_type).info("不满足基础规则\n")
  242. # 标题敏感词过滤
  243. elif any(word if word in weishi_title else False for word in
  244. cls.video_title_sensitive_words(log_type)) is True:
  245. Common.logger(log_type).info("标题已中敏感词:{}\n".format(weishi_title))
  246. # 用户名敏感词过滤
  247. elif any(word if word in user_name else False for word in
  248. cls.username_sensitive_words(log_type)) is True:
  249. Common.logger(log_type).info("用户名已中敏感词:{}\n".format(user_name))
  250. # 从已下载云文档去重
  251. elif str(video_id) in [j for m in Feishu.get_values_batch(log_type, 'weishi', "caa3fa") for j in m]:
  252. Common.logger(log_type).info("视频已下载:{}\n", video_title)
  253. # 从 云文档 去重:https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr
  254. elif str(video_id) in [j for n in Feishu.get_values_batch(log_type, 'weishi', "O7fCzr") for j in n]:
  255. Common.logger(log_type).info("视频已存在:{}\n", video_title)
  256. else:
  257. # 添加到已下载视频列表
  258. cls.video_count.append(video_id)
  259. # feeds工作表,插入首行
  260. Feishu.insert_columns(log_type, 'weishi', "O7fCzr", "ROWS", 1, 2)
  261. # 获取当前时间
  262. get_feeds_time = int(time.time())
  263. # 工作表 feeds 中写入数据
  264. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(int(get_feeds_time))),
  265. "推荐榜",
  266. str(video_id),
  267. video_title,
  268. int(video_play_cnt),
  269. int(video_comment_cnt),
  270. int(video_like_cnt),
  271. int(video_share_cnt),
  272. video_duration,
  273. video_resolution,
  274. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(int(video_send_time / 1000))),
  275. user_name,
  276. user_id,
  277. head_url,
  278. cover_url,
  279. video_url]]
  280. # 等待 1s,防止操作云文档太频繁,导致报错
  281. time.sleep(1)
  282. Feishu.update_values(log_type, 'weishi', "O7fCzr", "A2:T2", values)
  283. Common.logger(log_type).info("视频保存至云文档成功\n")
  284. time.sleep(random.randint(3, 5))
  285. # 每天抓取 50 条
  286. if len(cls.video_count) >= cls.crawler_count:
  287. Common.logger(log_type).info("已抓取{}条数据\n", len(cls.video_count))
  288. cls.video_count = []
  289. return
  290. except Exception as e:
  291. Common.logger(log_type).error("get_feeds异常:{}\n".format(e))
  292. # 下载/上传
  293. @classmethod
  294. def download_publish(cls, log_type, env):
  295. try:
  296. recommend_sheet = Feishu.get_values_batch(log_type, 'weishi', "O7fCzr")
  297. for i in range(1, len(recommend_sheet)):
  298. download_video_id = recommend_sheet[i][2]
  299. download_video_title = recommend_sheet[i][3]
  300. download_video_play_cnt = recommend_sheet[i][4]
  301. download_video_comment_cnt = recommend_sheet[i][5]
  302. download_video_like_cnt = recommend_sheet[i][6]
  303. download_video_share_cnt = recommend_sheet[i][7]
  304. download_video_duration = recommend_sheet[i][8]
  305. download_video_resolution = recommend_sheet[i][9]
  306. download_video_send_time = recommend_sheet[i][10]
  307. download_user_name = recommend_sheet[i][11]
  308. download_user_id = recommend_sheet[i][12]
  309. download_head_url = recommend_sheet[i][13]
  310. download_cover_url = recommend_sheet[i][14]
  311. download_video_url = recommend_sheet[i][15]
  312. # Common.logger(log_type).info("download_video_title:{}", download_video_title)
  313. # Common.logger(log_type).info("download_video_id:{}", download_video_id)
  314. # Common.logger(log_type).info("download_video_play_cnt:{}", download_video_play_cnt)
  315. # Common.logger(log_type).info("download_video_comment_cnt:{}", download_video_comment_cnt)
  316. # Common.logger(log_type).info("download_video_share_cnt:{}", download_video_share_cnt)
  317. # Common.logger(log_type).info("download_user_name:{}", download_user_name)
  318. # Common.logger(log_type).info("download_user_id:{}", download_user_id)
  319. # Common.logger(log_type).info("download_head_url:{}", download_head_url)
  320. # Common.logger(log_type).info("download_cover_url:{}", download_cover_url)
  321. Common.logger(log_type).info("正在判断第{}行:{}", i+1, download_video_title)
  322. Common.logger(log_type).info("like_cnt:{}", download_video_like_cnt)
  323. Common.logger(log_type).info("duration:{}", download_video_duration)
  324. Common.logger(log_type).info("resolution:{}", download_video_resolution)
  325. Common.logger(log_type).info("send_time:{}", download_video_send_time)
  326. Common.logger(log_type).info("video_url:{}", download_video_url)
  327. # 过滤空行
  328. if download_video_id is None or download_video_title is None:
  329. # 删除行或列,可选 ROWS、COLUMNS
  330. Feishu.dimension_range(log_type, 'weishi', "O7fCzr", "ROWS", i + 1, i + 1)
  331. Common.logger(log_type).warning("空行,已删除\n")
  332. return
  333. # 去重
  334. elif download_video_id in [j for m in Feishu.get_values_batch(log_type, 'weishi', "caa3fa") for j in m]:
  335. # 删除行或列,可选 ROWS、COLUMNS
  336. Feishu.dimension_range(log_type, 'weishi', "O7fCzr", "ROWS", i + 1, i + 1)
  337. Common.logger(log_type).info("视频已下载:{}\n", download_video_title)
  338. return
  339. else:
  340. # 下载封面
  341. Common.download_method(log_type, text="cover",
  342. d_name=str(download_video_title), d_url=str(download_cover_url))
  343. # 下载视频
  344. Common.download_method(log_type, text="video",
  345. d_name=str(download_video_title), d_url=str(download_video_url))
  346. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  347. with open("./videos/" + download_video_title
  348. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  349. f_a.write(str(download_video_id) + "\n" +
  350. str(download_video_title) + "\n" +
  351. str(download_video_duration) + "\n" +
  352. str(download_video_play_cnt) + "\n" +
  353. str(download_video_comment_cnt) + "\n" +
  354. str(download_video_like_cnt) + "\n" +
  355. str(download_video_share_cnt) + "\n" +
  356. str(download_video_resolution) + "\n" +
  357. str(int(time.mktime(
  358. time.strptime(download_video_send_time, "%Y/%m/%d %H:%M:%S")))) + "\n" +
  359. str(download_user_name) + "\n" +
  360. str(download_head_url) + "\n" +
  361. str(download_video_url) + "\n" +
  362. str(download_cover_url) + "\n" +
  363. str(cls.wesee_access_token))
  364. Common.logger(log_type).info("视频信息已保存至info.txt")
  365. # 上传视频
  366. Common.logger(log_type).info("开始上传视频:{}".format(download_video_title))
  367. our_video_id = Publish.upload_and_publish(log_type, env, "play")
  368. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  369. Common.logger(log_type).info("视频上传完成:{}", download_video_title)
  370. # 视频ID工作表,插入首行
  371. Feishu.insert_columns(log_type, 'weishi', "caa3fa", "ROWS", 1, 2)
  372. # 视频ID工作表,首行写入数据
  373. upload_time = int(time.time())
  374. values = [[str(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time))),
  375. "推荐榜",
  376. str(download_video_title),
  377. str(download_video_id),
  378. our_video_link,
  379. download_video_play_cnt,
  380. download_video_comment_cnt,
  381. download_video_like_cnt,
  382. download_video_share_cnt,
  383. download_video_duration,
  384. str(download_video_resolution),
  385. str(download_video_send_time),
  386. str(download_user_name),
  387. str(download_user_id),
  388. str(download_head_url),
  389. str(download_cover_url),
  390. str(download_video_url)]]
  391. time.sleep(1)
  392. Feishu.update_values(log_type, 'weishi', "caa3fa", "F2:W2", values)
  393. Common.logger(log_type).info("视频已保存至云文档:{}", download_video_title)
  394. # 删除行或列,可选 ROWS、COLUMNS
  395. Feishu.dimension_range(log_type, 'weishi', "O7fCzr", "ROWS", i + 1, i + 1)
  396. Common.logger(log_type).info("视频:{},下载/上传成功\n", download_video_title)
  397. return
  398. except Exception as e:
  399. Feishu.dimension_range(log_type, 'weishi', "O7fCzr", "ROWS", 2, 2)
  400. Common.logger(log_type).error("download_publish异常,已删除该条数据:{}\n", e)
  401. # 执行 下载/上传
  402. @classmethod
  403. def run_download_publish(cls, log_type, env):
  404. try:
  405. while True:
  406. if len(Feishu.get_values_batch(log_type, 'weishi', 'O7fCzr')) == 1:
  407. Common.logger(log_type).info("下载/上传完成\n")
  408. break
  409. else:
  410. cls.download_publish(log_type, env)
  411. time.sleep(random.randint(1, 3))
  412. except Exception as e:
  413. Common.logger(log_type).error("run_download_publish异常:{}", e)
  414. if __name__ == "__main__":
  415. # Recommend.get_feeds('weishi')
  416. Recommend.download_publish('weishi', 'dev')
  417. # print(Recommend.Referer)
  418. # print(Recommend.wesee_openid)
  419. # print(Recommend.wesee_openkey)
  420. # print(Recommend.wesee_personid)
  421. # print(Recommend.wesee_access_token)
  422. # print(Recommend.wesee_thr_appid)
  423. pass