kanyikan_recommend.py 13 KB

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