kanyikan_recommend.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/6/1
  4. import os
  5. import random
  6. import shutil
  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 Kanyikanrecommend:
  17. @classmethod
  18. def get_filter_word(cls, log_type, crawler):
  19. while True:
  20. filter_sheet = Feishu.get_values_batch(log_type, crawler, "rofdM5")
  21. if filter_sheet is None:
  22. Common.logger(log_type).info(f"filter_sheet:{filter_sheet}")
  23. time.sleep(1)
  24. continue
  25. # 敏感词库列表
  26. word_list = []
  27. for i in filter_sheet:
  28. for j in i:
  29. # 过滤空的单元格内容
  30. if j is None:
  31. pass
  32. else:
  33. word_list.append(j)
  34. return word_list
  35. @classmethod
  36. def download_rule(cls, video_dict):
  37. now = int(time.time())
  38. publish_day = int(int(now - video_dict["publish_time_stamp"]) / (3600*24))
  39. if (int(video_dict["video_width"]) or int(video_dict["video_height"]) >= 0) \
  40. and int(video_dict["duration"]) >= 40\
  41. and ((publish_day >= 7 and int(video_dict["play_cnt"]) >= 20000) or (publish_day < 7 and int(video_dict["play_cnt"]) >= 5000)):
  42. return True
  43. else:
  44. return False
  45. @classmethod
  46. def get_videoList(cls, log_type, crawler, env):
  47. while True:
  48. for page in range(1, 101):
  49. Common.logger(log_type).info(f"正在抓取第{page}页")
  50. try:
  51. session = Common.get_session(log_type)
  52. if session is None:
  53. time.sleep(1)
  54. continue
  55. url = 'https://search.weixin.qq.com/cgi-bin/recwxa/recwxavideolist?'
  56. header = {
  57. "Connection": "keep-alive",
  58. "content-type": "application/json",
  59. "Accept-Encoding": "gzip,compress,br,deflate",
  60. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) "
  61. "AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/8.0.18(0x18001236) "
  62. "NetType/WIFI Language/zh_CN",
  63. "Referer": "https://servicewechat.com/wxbb9a805eb4f9533c/234/page-frame.html",
  64. }
  65. params = {
  66. 'session': session,
  67. "offset": 0,
  68. "wxaVersion": "3.9.2",
  69. "count": "10",
  70. "channelid": "208",
  71. "scene": '310',
  72. "subscene": '1089',
  73. "clientVersion": '8.0.18',
  74. "sharesearchid": '0',
  75. "nettype": 'wifi',
  76. "switchprofile": "0",
  77. "switchnewuser": "0",
  78. }
  79. urllib3.disable_warnings()
  80. response = requests.get(url=url, headers=header, params=params, proxies=proxies, verify=False)
  81. if "data" not in response.text:
  82. Common.logger(log_type).info("获取视频list时,session过期,随机睡眠 31-50 秒")
  83. # 如果返回空信息,则随机睡眠 31-40 秒
  84. time.sleep(random.randint(31, 40))
  85. continue
  86. elif "items" not in response.json()["data"]:
  87. Common.logger(log_type).info(f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
  88. # 如果返回空信息,则随机睡眠 1-3 分钟
  89. time.sleep(random.randint(60, 180))
  90. continue
  91. feeds = response.json().get("data", {}).get("items", "")
  92. if feeds == "":
  93. Common.logger(log_type).info(f"feeds:{feeds}")
  94. time.sleep(random.randint(31, 40))
  95. continue
  96. for i in range(len(feeds)):
  97. try:
  98. video_title = feeds[i].get("title", "").strip().replace("\n", "") \
  99. .replace("/", "").replace("\\", "").replace("\r", "") \
  100. .replace(":", "").replace("*", "").replace("?", "") \
  101. .replace("?", "").replace('"', "").replace("<", "") \
  102. .replace(">", "").replace("|", "").replace(" ", "") \
  103. .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
  104. .replace("'", "").replace("#", "").replace("Merge", "")
  105. publish_time_stamp = feeds[i].get("date", 0)
  106. publish_time_str = time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(publish_time_stamp))
  107. # 获取播放地址
  108. if "videoInfo" not in feeds[i]:
  109. video_url = ""
  110. elif "mpInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  111. if len(feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"]) > 2:
  112. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][2]["url"]
  113. else:
  114. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][0]["url"]
  115. elif "ctnInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  116. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["ctnInfo"]["urlInfo"][0]["url"]
  117. else:
  118. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["urlInfo"][0]["url"]
  119. video_dict = {
  120. "video_title": video_title,
  121. "video_id": feeds[i].get("videoId", ""),
  122. "play_cnt": feeds[i].get("playCount", 0),
  123. "like_cnt": feeds[i].get("liked_cnt", 0),
  124. "comment_cnt": feeds[i].get("comment_cnt", 0),
  125. "share_cnt": feeds[i].get("shared_cnt", 0),
  126. "duration": feeds[i].get("mediaDuration", 0),
  127. "video_width": feeds[i].get("short_video_info", {}).get("width", 0),
  128. "video_height": feeds[i].get("short_video_info", {}).get("height", 0),
  129. "publish_time_stamp": publish_time_stamp,
  130. "publish_time_str": publish_time_str,
  131. "user_name": feeds[i].get("source", "").strip().replace("\n", ""),
  132. "user_id": feeds[i].get("openid", ""),
  133. "avatar_url": feeds[i].get("bizIcon", ""),
  134. "cover_url": feeds[i].get("thumbUrl", ""),
  135. "video_url": video_url,
  136. "session": session,
  137. }
  138. for k, v in video_dict.items():
  139. Common.logger(log_type).info(f"{k}:{v}")
  140. if video_dict["video_id"] == "" \
  141. or video_dict["video_title"] == ""\
  142. or video_dict["video_url"] == "":
  143. Common.logger(log_type).info("无效视频\n")
  144. elif cls.download_rule(video_dict) is False:
  145. Common.logger(log_type).info("不满足抓取规则\n")
  146. elif any(str(word) if str(word) in video_title else False for word in cls.get_filter_word(log_type, crawler)) is True:
  147. Common.logger(log_type).info("视频已中过滤词\n")
  148. elif video_dict["video_id"] in [j for i in Feishu.get_values_batch(log_type, crawler, "ho98Ov") for j in i]:
  149. Common.logger(log_type).info("视频已下载\n")
  150. elif video_dict["video_id"] in [j for i in Feishu.get_values_batch(log_type, crawler, "20ce0c") for j in i]:
  151. Common.logger(log_type).info("视频已下载\n")
  152. else:
  153. cls.download_publish(log_type, crawler, video_dict, env)
  154. except Exception as e:
  155. Common.logger(log_type).error(f"抓取单条视频异常:{e}\n")
  156. except Exception as e:
  157. Common.logger(log_type).error(f"抓取第{page}页时异常:{e}\n")
  158. @classmethod
  159. def download_publish(cls, log_type, crawler, video_dict, env):
  160. Common.download_method(log_type, "video", video_dict["video_title"], video_dict["video_url"])
  161. try:
  162. if os.path.getsize(f"./videos/{video_dict['video_title']}/video.mp4") == 0:
  163. # 删除视频文件夹
  164. shutil.rmtree(f"./videos/{video_dict['video_title']}")
  165. Common.logger(log_type).info("视频size=0,删除成功\n")
  166. return
  167. except FileNotFoundError:
  168. # 删除视频文件夹
  169. shutil.rmtree(f"./videos/{video_dict['video_title']}")
  170. Common.logger(log_type).info("视频文件不存在,删除文件夹成功\n")
  171. return
  172. Common.download_method(log_type, "cover", video_dict["video_title"], video_dict["cover_url"])
  173. with open(f"./videos/{video_dict['video_title']}/info.txt", "a", encoding="utf8") as f_a2:
  174. f_a2.write(str(video_dict['video_id']) + "\n" +
  175. str(video_dict['video_title']) + "\n" +
  176. str(video_dict['duration']) + "\n" +
  177. str(video_dict['play_cnt']) + "\n" +
  178. str(video_dict['comment_cnt']) + "\n" +
  179. str(video_dict['like_cnt']) + "\n" +
  180. str(video_dict['share_cnt']) + "\n" +
  181. f'{video_dict["video_width"]}*{video_dict["video_height"]}' + "\n" +
  182. str(video_dict["publish_time_stamp"]) + "\n" +
  183. str(video_dict["user_name"]) + "\n" +
  184. str(video_dict["avatar_url"]) + "\n" +
  185. str(video_dict["video_url"]) + "\n" +
  186. str(video_dict["cover_url"]) + "\n" +
  187. f"kanyikan-recommend-{int(time.time())}")
  188. Common.logger("recommend").info("==========视频信息已保存至info.txt==========")
  189. # 上传视频
  190. our_video_id = Publish.upload_and_publish(log_type=log_type,
  191. crawler=crawler,
  192. strategy="推荐抓取策略",
  193. our_uid="recommend",
  194. env=env,
  195. oss_endpoint="out")
  196. if env == "dev":
  197. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  198. else:
  199. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  200. if our_video_id is None:
  201. try:
  202. # 删除视频文件夹
  203. shutil.rmtree(f"./videos/{video_dict['video_title']}")
  204. return
  205. except FileNotFoundError:
  206. return
  207. # 保存视频信息到云文档:
  208. Feishu.insert_columns(log_type, crawler, "20ce0c", "ROWS", 1, 2)
  209. # 看一看+ ,视频ID工作表,首行写入数据
  210. upload_time = int(time.time())
  211. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  212. "推荐榜",
  213. str(video_dict["video_id"]),
  214. str(video_dict["video_title"]),
  215. our_video_link,
  216. video_dict["play_cnt"],
  217. video_dict["comment_cnt"],
  218. video_dict["like_cnt"],
  219. video_dict["share_cnt"],
  220. video_dict["duration"],
  221. f'{video_dict["video_width"]}*{video_dict["video_height"]}',
  222. video_dict["publish_time_str"],
  223. video_dict["user_name"],
  224. video_dict["user_id"],
  225. video_dict["avatar_url"],
  226. video_dict["cover_url"],
  227. video_dict["video_url"]]]
  228. time.sleep(0.5)
  229. Feishu.update_values(log_type, crawler, "20ce0c", "F2:Z2", values)
  230. Common.logger(log_type).info("视频信息保存至云文档成功\n")
  231. if __name__ == "__main__":
  232. print(Kanyikanrecommend.get_filter_word("recommend", "kanyikan"))
  233. print(int(time.mktime(time.strptime("2021-06-01 00:00:00", "%Y-%m-%d %H:%M:%S"))))
  234. pass