kanyikan_recommend.py 13 KB

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