kanyikan_recommend.py 13 KB

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