weishi_recommend.py 22 KB

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