kanyikan_moment.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/1/31
  4. """
  5. 看一看+小程序: 朋友圈榜单
  6. """
  7. import time
  8. import requests
  9. import urllib3
  10. from common.common import Common
  11. from common.feishu import Feishu
  12. from common.publish import Publish
  13. proxies = {"http": None, "https": None}
  14. class Moment:
  15. # 抓取基础规则
  16. @staticmethod
  17. def download_rule(video_dict):
  18. """
  19. 抓取基础规则
  20. """
  21. if int(float(video_dict['duration'])) >= 60:
  22. if int(video_dict['video_width']) >= 0 or int(video_dict['video_height']) >= 0:
  23. if int(video_dict['play_cnt']) >= 100000:
  24. if int(video_dict['like_cnt']) >= 0:
  25. if int(video_dict['share_cnt']) >= 0:
  26. return True
  27. else:
  28. return False
  29. else:
  30. return False
  31. else:
  32. return False
  33. return False
  34. return False
  35. # 获取推荐视频列表
  36. @classmethod
  37. def get_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine, moment_video_id):
  38. url = "https://search.weixin.qq.com/cgi-bin/recwxa/snsgetvideoinfo?"
  39. headers = {
  40. "content-type": "application/json",
  41. "Accept-Encoding": "gzip,compress,br,deflate",
  42. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)"
  43. " AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
  44. " MicroMessenger/8.0.20(0x18001442) NetType/WIFI Language/zh_CN",
  45. "Referer": "https://servicewechat.com/wxbb9a805eb4f9533c/236/page-frame.html"
  46. }
  47. # videoid = random.choice(Feishu.get_sheet_content(log_type, crawler, 'iK58HX'))
  48. params = {
  49. "vid": moment_video_id,
  50. "openid": "1924336296754305",
  51. "model": "iPhone 11<iPhone12,1>14.7.1",
  52. "sharesearchid": "8406805193800900989",
  53. "shareOpenid": "oh_m45YffSEGxvDH--6s6g9ZkPxg",
  54. }
  55. try:
  56. urllib3.disable_warnings()
  57. r = requests.get(url=url, headers=headers, params=params, proxies=proxies, verify=False)
  58. if r.status_code != 200:
  59. Common.logger(log_type, crawler).warning(f"response.status_code:{r.status_code}")
  60. Common.logger(log_type, crawler).warning(f"response.text:{r.text}\n")
  61. elif r.json()["errcode"] != 0:
  62. Common.logger(log_type, crawler).warning(f"msg:{r.json()['msg']}\n")
  63. elif "rec_video_list" not in r.json()["data"]:
  64. Common.logger(log_type, crawler).warning(f"该视频没有推荐列表\n")
  65. else:
  66. feeds = r.json()["data"]["rec_video_list"]
  67. for i in range(len(feeds)):
  68. # video_id
  69. if "vid" in feeds[i]:
  70. video_id = feeds[i]["vid"]
  71. else:
  72. video_id = 0
  73. # video_title
  74. if "title" in feeds[i]:
  75. video_title = feeds[i]["title"].strip().replace("\n", "") \
  76. .replace("/", "").replace("\\", "").replace("\r", "") \
  77. .replace(":", "").replace("*", "").replace("?", "") \
  78. .replace("?", "").replace('"', "").replace("<", "") \
  79. .replace(">", "").replace("|", "").replace(" ", "") \
  80. .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
  81. .replace("小年糕", "").replace("#", "").replace("Merge", "")
  82. else:
  83. video_title = 0
  84. # video_play_cnt
  85. if "played_cnt" in feeds[i]:
  86. video_play_cnt = feeds[i]["played_cnt"]
  87. else:
  88. video_play_cnt = 0
  89. # video_comment_cnt
  90. if "comment_cnt" in feeds[i]:
  91. video_comment_cnt = feeds[i]["comment_cnt"]
  92. else:
  93. video_comment_cnt = 0
  94. # video_liked_cnt
  95. if "liked_cnt" in feeds[i]:
  96. video_liked_cnt = feeds[i]["liked_cnt"]
  97. else:
  98. video_liked_cnt = 0
  99. # video_share_cnt
  100. if "shared_cnt" in feeds[i]:
  101. video_share_cnt = feeds[i]["shared_cnt"]
  102. else:
  103. video_share_cnt = 0
  104. # video_duration
  105. if "duration" in feeds[i]:
  106. video_duration = feeds[i]["duration"]
  107. else:
  108. video_duration = 0
  109. # video_width / video_height
  110. if "width" in feeds[i] or "height" in feeds[i]:
  111. video_width = feeds[i]["width"]
  112. video_height = feeds[i]["height"]
  113. else:
  114. video_width = 0
  115. video_height = 0
  116. # video_send_time
  117. if "upload_time" in feeds[i]:
  118. publish_time = feeds[i]["upload_time"]
  119. else:
  120. publish_time = 0
  121. # user_name
  122. if "user_info" not in feeds[i]:
  123. user_name = 0
  124. elif "nickname" not in feeds[i]["user_info"]:
  125. user_name = 0
  126. else:
  127. user_name = feeds[i]["user_info"]["nickname"].strip().replace("\n", "")
  128. # user_id
  129. if "user_info" not in feeds[i]:
  130. user_id = 0
  131. elif "openid" not in feeds[i]["user_info"]:
  132. user_id = 0
  133. else:
  134. user_id = feeds[i]["user_info"]["openid"]
  135. # head_url
  136. if "user_info" not in feeds[i]:
  137. avatar_url = 0
  138. elif "headimg_url" not in feeds[i]["user_info"]:
  139. avatar_url = 0
  140. else:
  141. avatar_url = feeds[i]["user_info"]["headimg_url"]
  142. # cover_url
  143. if "cover_url" not in feeds[i]:
  144. cover_url = 0
  145. else:
  146. cover_url = feeds[i]["cover_url"]
  147. # video_url
  148. if "play_info" not in feeds[i]:
  149. video_url = 0
  150. elif "items" not in feeds[i]["play_info"]:
  151. video_url = 0
  152. else:
  153. video_url = feeds[i]["play_info"]["items"][-1]["play_url"]
  154. video_dict = {
  155. 'video_id': video_id,
  156. 'video_title': video_title,
  157. 'duration': video_duration,
  158. 'play_cnt': video_play_cnt,
  159. 'comment_cnt': video_comment_cnt,
  160. 'like_cnt': video_liked_cnt,
  161. 'share_cnt': video_share_cnt,
  162. 'video_width': video_width,
  163. 'video_height': video_height,
  164. 'publish_time': publish_time,
  165. 'user_name': user_name,
  166. 'user_id': user_id,
  167. 'avatar_url': avatar_url,
  168. 'video_url': video_url,
  169. 'cover_url': cover_url,
  170. 'session': f'kanyikan_moment_{int(time.time())}',
  171. }
  172. Common.logger(log_type, crawler).info("video_title:{}", video_title)
  173. Common.logger(log_type, crawler).info("video_play_cnt:{}", video_play_cnt)
  174. Common.logger(log_type, crawler).info("video_duration:{}", video_duration)
  175. Common.logger(log_type, crawler).info("video_url:{}", video_url)
  176. # 过滤无效视频
  177. if video_id == 0 or video_title == 0 or video_duration == 0 or publish_time == 0 or user_id == 0\
  178. or avatar_url == 0 or cover_url == 0 or video_url == 0:
  179. Common.logger(log_type, crawler).warning("无效视频\n")
  180. # 抓取基础规则
  181. elif cls.download_rule(video_dict) is False:
  182. Common.logger(log_type, crawler).info("不满足基础规则\n")
  183. elif int(publish_time) < 1659283200:
  184. Common.logger(log_type, crawler).info(f'发布时间{time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(publish_time))} < 2022-08-01\n')
  185. # 过滤词库
  186. elif any(word if word in video_title else False for word in Feishu.get_sheet_content(log_type, crawler, 'rofdM5')) is True:
  187. Common.logger(log_type, crawler).info("视频已中过滤词\n")
  188. # 已下载视频表去重
  189. elif video_id in [j for m in Feishu.get_values_batch(log_type, crawler, "20ce0c") for j in m]:
  190. Common.logger(log_type, crawler).info("视频已下载\n")
  191. else:
  192. cls.download_publish(log_type, crawler, strategy, oss_endpoint, env, video_dict)
  193. except Exception as e:
  194. Common.logger(log_type, crawler).error(f"get_videos异常:{e}\n")
  195. # 下载/上传视频
  196. @classmethod
  197. def download_publish(cls, log_type, crawler, strategy, oss_endpoint, env, video_dict):
  198. try:
  199. # 过滤空行及空标题视频
  200. if video_dict['video_id'] == 0 \
  201. or video_dict['video_title'] == 0\
  202. or video_dict['video_url'] == 0:
  203. Common.logger(log_type, crawler).info("无效视频\n")
  204. # # 视频的抓取时间小于 2 天
  205. # elif int(time.time()) - v_push_time > 172800:
  206. # Common.logger(log_type, crawler).info("抓取时间超过2天:{}", video_dict['video_title'])
  207. # # 删除行或列,可选 ROWS、COLUMNS
  208. # Feishu.dimension_range("tGqZMX", "ROWS", i + 1, i + 1)
  209. # return
  210. # 视频发布时间不小于 2021-06-01 00:00:00
  211. elif video_dict['publish_time'] < 1622476800:
  212. Common.logger(log_type, crawler).info(f'发布时间{time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(video_dict["publish_time"]))} < 2021-06-01\n')
  213. else:
  214. # 下载封面
  215. Common.download_method(log_type=log_type, crawler=crawler, text="cover",
  216. title=video_dict['video_title'], url=video_dict['cover_url'])
  217. # 下载视频
  218. Common.download_method(log_type=log_type, crawler=crawler, text="video",
  219. title=video_dict['video_title'], url=video_dict['video_url'])
  220. # 保存视频信息至 "./{crawler}/videos/{video_dict['video_title']}/info.txt"
  221. Common.save_video_info(log_type, crawler, video_dict)
  222. # 上传视频
  223. Common.logger(log_type, crawler).info(f"开始上传视频:{video_dict['video_title']}")
  224. our_video_id = Publish.upload_and_publish(log_type=log_type,
  225. crawler=crawler,
  226. strategy=strategy,
  227. oss_endpoint=oss_endpoint,
  228. our_uid="kanyikan_moment",
  229. env=env)
  230. if env == 'dev':
  231. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  232. else:
  233. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  234. Common.logger(log_type, crawler).info("视频上传完成:{}", video_dict['video_title'])
  235. # 保存视频 ID 到云文档
  236. Common.logger(log_type, crawler).info(f"保存视频ID至云文档:{video_dict['video_title']}")
  237. # 视频ID工作表,插入首行
  238. Feishu.insert_columns(log_type, crawler, "20ce0c", "ROWS", 1, 2)
  239. # 视频ID工作表,首行写入数据
  240. upload_time = int(time.time())
  241. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  242. "朋友圈",
  243. str(video_dict['video_id']),
  244. str(video_dict['video_title']),
  245. our_video_link,
  246. video_dict['play_cnt'],
  247. video_dict['comment_cnt'],
  248. video_dict['like_cnt'],
  249. video_dict['share_cnt'],
  250. video_dict['duration'],
  251. f"{video_dict['video_width']}*{video_dict['video_height']}",
  252. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(video_dict["publish_time"])),
  253. video_dict['user_name'],
  254. video_dict['user_id'],
  255. video_dict['head_url'],
  256. video_dict['cover_url'],
  257. video_dict['video_url']
  258. ]]
  259. time.sleep(1)
  260. Feishu.update_values(log_type, crawler, "20ce0c", "F2:W2", values)
  261. Common.logger(log_type, crawler).info('下载/上传成功\n')
  262. except Exception as e:
  263. Common.logger(log_type, crawler).error(f"download_publish异常:{e}\n")
  264. if __name__ == "__main__":
  265. kanyikan_moment = Moment()
  266. pass