follow.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/6/15
  4. import os
  5. import sys
  6. import time
  7. import requests
  8. import urllib3
  9. sys.path.append(os.getcwd())
  10. from main.publish import Publish
  11. from main.common import Common
  12. from main.feishu_lib import Feishu
  13. proxies = {"http": None, "https": None}
  14. class DownloadFollow:
  15. # 配置微信号
  16. Referer = Feishu.get_range_value("follow", "9fTK1f", "C3:C3")[0]
  17. wesee_openid = Feishu.get_range_value("follow", "9fTK1f", "C4:C4")[0]
  18. wesee_openkey = Feishu.get_range_value("follow", "9fTK1f", "C5:C5")[0]
  19. wesee_personid = Feishu.get_range_value("follow", "9fTK1f", "C6:C6")[0]
  20. wesee_access_token = Feishu.get_range_value("follow", "9fTK1f", "C7:C7")[0]
  21. wesee_thr_appid = Feishu.get_range_value("follow", "9fTK1f", "C8:C8")[0]
  22. # 翻页参数
  23. attachInfo = ""
  24. # 过滤词库
  25. @classmethod
  26. def sensitive_words(cls):
  27. # 词库列表
  28. word_list = []
  29. # 从云文档读取所有词,添加到词库列表
  30. lists = Feishu.get_values_batch("follow", "2Oxf8C")
  31. for i in lists:
  32. for j in i:
  33. # 过滤空的单元格内容
  34. if j is None:
  35. pass
  36. else:
  37. word_list.append(j)
  38. return word_list
  39. # 下载规则
  40. @staticmethod
  41. def download_rule(d_duration, d_width, d_height, d_play_cnt, d_like_cnt, d_share_cnt):
  42. """
  43. 下载视频的基本规则
  44. :param d_duration: 时长
  45. :param d_width: 宽
  46. :param d_height: 高
  47. :param d_play_cnt: 播放量
  48. :param d_like_cnt: 点赞量
  49. :param d_share_cnt: 分享量
  50. :return: 满足规则,返回 True;反之,返回 False
  51. """
  52. if int(float(d_duration)) >= 20:
  53. if int(d_width) >= 0 or int(d_height) >= 0:
  54. if int(d_play_cnt) >= 0:
  55. if int(d_like_cnt) >= 0 or int(d_share_cnt) >= 0:
  56. return True
  57. else:
  58. return False
  59. else:
  60. return False
  61. return False
  62. return False
  63. # 抓取列表
  64. @classmethod
  65. def get_feeds(cls):
  66. """
  67. 1.从微视小程序首页推荐,获取视频列表
  68. 2.先在 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=caa3fa 中去重
  69. 3.再从 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr 中去重
  70. 4.添加视频信息至 https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr
  71. """
  72. url = "https://api.weishi.qq.com/trpc.weishi.weishi_h5_proxy.weishi_h5_proxy/WxminiGetFollowFeedList"
  73. headers = {
  74. "content-type": "application/json",
  75. "Accept-Encoding": "gzip,compress,br,deflate",
  76. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)"
  77. " AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
  78. " MicroMessenger/8.0.20(0x18001442) NetType/WIFI Language/zh_CN",
  79. "Referer": str(cls.Referer)
  80. }
  81. cookies = {
  82. "wesee_authtype": "3",
  83. "wesee_openid": str(cls.wesee_openid),
  84. "wesee_openkey": str(cls.wesee_openkey),
  85. "wesee_personid": str(cls.wesee_personid),
  86. "wesee_refresh_token": "",
  87. "wesee_access_token": str(cls.wesee_access_token),
  88. "wesee_thr_appid": str(cls.wesee_thr_appid),
  89. "wesee_ichid": "8"
  90. }
  91. json_data = {
  92. "req_body": {
  93. "attachInfo": str(cls.attachInfo)
  94. },
  95. "req_header": {
  96. "mapExt": "{\"imageSize\":\"480\",\"adaptScene\":\"PicHDWebpLimitScene\","
  97. "\"weseeCostTag\":\"WxMiniProgram\"}"
  98. }
  99. }
  100. try:
  101. urllib3.disable_warnings()
  102. r = requests.post(headers=headers, url=url, cookies=cookies, json=json_data, proxies=proxies,
  103. verify=False)
  104. if r.json()["rsp_header"]["errMsg"] != "":
  105. Common.logger("follow").error("errMsg:{}", r.json()["rsp_header"]["errMsg"])
  106. cls.attachInfo = r.json()["rsp_body"]["attachInfo"]
  107. feeds = r.json()["rsp_body"]["feeds"]
  108. for i in range(len(feeds)):
  109. # 视频标题过滤话题及处理特殊字符
  110. weishi_title = feeds[i]["desc"]
  111. title_split1 = weishi_title.split(" #")
  112. if title_split1[0] != "":
  113. title1 = title_split1[0]
  114. else:
  115. title1 = title_split1[-1]
  116. title_split2 = title1.split(" #")
  117. if title_split2[0] != "":
  118. title2 = title_split2[0]
  119. else:
  120. title2 = title_split2[-1]
  121. title_split3 = title2.split("@")
  122. if title_split3[0] != "":
  123. title3 = title_split3[0]
  124. else:
  125. title3 = title_split3[-1]
  126. # 视频标题
  127. video_title = title3.strip().replace("\n", "") \
  128. .replace("/", "").replace("快手", "").replace(" ", "") \
  129. .replace(" ", "").replace("&NBSP", "").replace("\r", "") \
  130. .replace("#", "").replace(".", "。").replace("\\", "") \
  131. .replace(":", "").replace("*", "").replace("?", "") \
  132. .replace("?", "").replace('"', "").replace("<", "") \
  133. .replace(">", "").replace("|", "").replace("微视", "")
  134. # 视频 ID
  135. if "id" not in feeds[i]["video"]:
  136. video_id = 0
  137. else:
  138. video_id = feeds[i]["video"]["id"]
  139. # 播放数
  140. if "playNum" not in feeds[i]["ugcData"]:
  141. video_play_cnt = 0
  142. else:
  143. video_play_cnt = feeds[i]["ugcData"]["playNum"]
  144. # 点赞数
  145. if "dingCount" not in feeds[i]["ugcData"]:
  146. video_like_cnt = 0
  147. else:
  148. video_like_cnt = feeds[i]["ugcData"]["dingCount"]
  149. # 分享数
  150. if "shareNum" not in feeds[i]["ugcData"]:
  151. video_share_cnt = 0
  152. else:
  153. video_share_cnt = feeds[i]["ugcData"]["shareNum"]
  154. # 评论数
  155. if "totalCommentNum" not in feeds[i]["ugcData"]:
  156. video_comment_cnt = 0
  157. else:
  158. video_comment_cnt = feeds[i]["ugcData"]["totalCommentNum"]
  159. # 视频时长
  160. if "duration" not in feeds[i]["video"]:
  161. video_duration = 0
  162. else:
  163. video_duration = int(int(feeds[i]["video"]["duration"]) / 1000)
  164. # 视频宽高
  165. if "width" not in feeds[i]["video"] or "height" not in feeds[i]["video"]:
  166. video_width = 0
  167. video_height = 0
  168. video_resolution = str(video_width) + "*" + str(video_height)
  169. else:
  170. video_width = feeds[i]["video"]["width"]
  171. video_height = feeds[i]["video"]["height"]
  172. video_resolution = str(video_width) + "*" + str(video_height)
  173. # 视频发布时间
  174. if "createTime" not in feeds[i]:
  175. video_send_time = 0
  176. else:
  177. video_send_time = int(feeds[i]["createTime"]) * 1000
  178. # 用户昵称
  179. user_name = feeds[i]["poster"]["nick"].strip().replace("\n", "") \
  180. .replace("/", "").replace("快手", "").replace(" ", "") \
  181. .replace(" ", "").replace("&NBSP", "").replace("\r", "").replace("微视", "")
  182. # 用户 ID
  183. user_id = feeds[i]["poster"]["id"]
  184. # 用户头像地址
  185. if "thumbURL" not in feeds[i]["material"] and "avatar" not in feeds[i]["poster"]:
  186. head_url = 0
  187. elif "thumbURL" in feeds[i]["material"]:
  188. head_url = feeds[i]["material"]["thumbURL"]
  189. else:
  190. head_url = feeds[i]["poster"]["avatar"]
  191. # 视频封面地址
  192. if len(feeds[i]["images"]) == 0:
  193. cover_url = 0
  194. else:
  195. cover_url = feeds[i]["images"][0]["url"]
  196. # 视频播放地址
  197. if "url" not in feeds[i]["video"]:
  198. video_url = 0
  199. else:
  200. video_url = feeds[i]["video"]["url"]
  201. Common.logger("follow").info("video_title:{}".format(video_title))
  202. Common.logger("follow").info("video_id:{}".format(video_id))
  203. Common.logger("follow").info("video_play_cnt:{}".format(video_play_cnt))
  204. Common.logger("follow").info("video_like_cnt:{}".format(video_like_cnt))
  205. Common.logger("follow").info("video_share_cnt:{}".format(video_share_cnt))
  206. # Common.logger("follow").info("video_comment_cnt:{}".format(video_comment_cnt))
  207. Common.logger("follow").info("video_duration:{}秒".format(video_duration))
  208. # Common.logger("follow").info("video_resolution:{}".format(video_resolution))
  209. Common.logger("follow").info(
  210. "video_send_time:{}".format(time.strftime(
  211. "%Y/%m/%d %H:%M:%S", time.localtime(int(video_send_time) / 1000))))
  212. Common.logger("follow").info("user_name:{}".format(user_name))
  213. # Common.logger("follow").info("user_id:{}".format(user_id))
  214. # Common.logger("follow").info("head_url:{}".format(head_url))
  215. # Common.logger("follow").info("cover_url:{}".format(cover_url))
  216. Common.logger("follow").info("video_url:{}".format(video_url))
  217. # 过滤无效视频
  218. if video_id == 0 or video_duration == 0 or video_send_time == 0 or head_url == 0 \
  219. or cover_url == 0 or video_url == 0:
  220. Common.logger("follow").info("无效视频")
  221. # 判断基础规则
  222. elif cls.download_rule(video_duration, video_width, video_height,
  223. video_play_cnt, video_like_cnt, video_share_cnt) is False:
  224. Common.logger("follow").info("不满足基础规则")
  225. # 判断敏感词
  226. elif any(word if word in weishi_title else False for word in cls.sensitive_words()) is True:
  227. Common.logger("follow").info("视频已中敏感词:{}".format(weishi_title))
  228. # 从 云文档 去重:https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=caa3fa
  229. elif video_id in [j for m in Feishu.get_values_batch("follow", "caa3fa") for j in m]:
  230. Common.logger("follow").info("该视频已下载:{}", video_title)
  231. # 从 云文档 去重:https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=O7fCzr
  232. elif video_id in [j for n in Feishu.get_values_batch("follow", "PamIy1") for j in n]:
  233. Common.logger("follow").info("该视频已在feeds中:{}", video_title)
  234. else:
  235. Common.logger("follow").info("该视频未下载,添加至feeds中:{}".format(video_title))
  236. # feeds工作表,插入首行
  237. time.sleep(1)
  238. Feishu.insert_columns("follow", "PamIy1", "ROWS", 1, 2)
  239. # 获取当前时间
  240. get_feeds_time = int(time.time())
  241. # 云文档,工作表中写入数据
  242. values = [[str(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(get_feeds_time))),
  243. "关注榜",
  244. video_id,
  245. video_title,
  246. video_play_cnt,
  247. video_comment_cnt,
  248. video_like_cnt,
  249. video_share_cnt,
  250. video_duration,
  251. video_resolution,
  252. time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(int(video_send_time) / 1000)),
  253. user_name,
  254. user_id,
  255. head_url,
  256. cover_url,
  257. video_url]]
  258. # 等待 1s,防止操作云文档太频繁,导致报错
  259. time.sleep(1)
  260. Feishu.update_values("follow", "PamIy1", "A2:P2", values)
  261. except Exception as e:
  262. Common.logger("follow").error("抓取关注列表异常:{}", e)
  263. # 下载及上传
  264. @classmethod
  265. def download_publish(cls):
  266. try:
  267. for i in range(1, len(Feishu.get_values_batch("follow", "PamIy1")) + 1):
  268. time.sleep(1)
  269. download_video_id = Feishu.get_values_batch("follow", "PamIy1")[i][2]
  270. download_video_title = Feishu.get_values_batch("follow", "PamIy1")[i][3]
  271. download_video_play_cnt = Feishu.get_values_batch("follow", "PamIy1")[i][4]
  272. download_video_comment_cnt = Feishu.get_values_batch("follow", "PamIy1")[i][5]
  273. download_video_like_cnt = Feishu.get_values_batch("follow", "PamIy1")[i][6]
  274. download_video_share_cnt = Feishu.get_values_batch("follow", "PamIy1")[i][7]
  275. download_video_duration = Feishu.get_values_batch("follow", "PamIy1")[i][8]
  276. download_video_resolution = Feishu.get_values_batch("follow", "PamIy1")[i][9]
  277. # download_video_width = download_video_resolution.split("*")[0]
  278. # download_video_height = download_video_resolution.split("*")[-1]
  279. download_video_send_time = Feishu.get_values_batch("follow", "PamIy1")[i][10]
  280. download_user_name = Feishu.get_values_batch("follow", "PamIy1")[i][11]
  281. download_user_id = Feishu.get_values_batch("follow", "PamIy1")[i][12]
  282. download_head_url = Feishu.get_values_batch("follow", "PamIy1")[i][13]
  283. download_cover_url = Feishu.get_values_batch("follow", "PamIy1")[i][14]
  284. download_video_url = Feishu.get_values_batch("follow", "PamIy1")[i][15]
  285. # Common.logger("follow").info("download_video_id:{}", download_video_id)
  286. # Common.logger("follow").info("download_video_title:{}", download_video_title)
  287. # Common.logger("follow").info("download_video_play_cnt:{}", download_video_play_cnt)
  288. # Common.logger("follow").info("download_video_comment_cnt:{}", download_video_comment_cnt)
  289. # Common.logger("follow").info("download_video_like_cnt:{}", download_video_like_cnt)
  290. # Common.logger("follow").info("download_video_share_cnt:{}", download_video_share_cnt)
  291. # Common.logger("follow").info("download_video_duration:{}", download_video_duration)
  292. # Common.logger("follow").info("download_video_resolution:{}", download_video_resolution)
  293. # Common.logger("follow").info("download_video_send_time:{}", download_video_send_time)
  294. # Common.logger("follow").info("download_user_name:{}", download_user_name)
  295. # Common.logger("follow").info("download_user_id:{}", download_user_id)
  296. # Common.logger("follow").info("download_head_url:{}", download_head_url)
  297. # Common.logger("follow").info("download_cover_url:{}", download_cover_url)
  298. # Common.logger("follow").info("download_video_url:{}", download_video_url)
  299. Common.logger("follow").info("正在判断第{}行,视频:{}", i, download_video_title)
  300. # 过滤空行
  301. if download_video_id is None \
  302. or download_video_id == ""\
  303. or download_video_title is None \
  304. or download_video_title == "":
  305. Common.logger("follow").warning("空行,删除")
  306. # 删除行或列,可选 ROWS、COLUMNS
  307. Feishu.dimension_range("follow", "PamIy1", "ROWS", i + 1, i + 1)
  308. return
  309. # 去重
  310. elif download_video_id in [j for m in Feishu.get_values_batch("follow", "caa3fa") for j in m]:
  311. Common.logger("follow").info("该视频已下载:{}", download_video_title)
  312. # 删除行或列,可选 ROWS、COLUMNS
  313. Feishu.dimension_range("follow", "PamIy1", "ROWS", i + 1, i + 1)
  314. return
  315. else:
  316. Common.logger("follow").info("开始下载视频:{}", download_video_title)
  317. # 下载封面
  318. Common.download_method(job="follow", text="cover",
  319. d_name=str(download_video_title), d_url=str(download_cover_url))
  320. # 下载视频
  321. Common.download_method(job="follow", text="video",
  322. d_name=str(download_video_title), d_url=str(download_video_url))
  323. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  324. with open("./videos/" + download_video_title
  325. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  326. f_a.write(str(download_video_id) + "\n" +
  327. str(download_video_title) + "\n" +
  328. str(download_video_duration) + "\n" +
  329. str(download_video_play_cnt) + "\n" +
  330. str(download_video_comment_cnt) + "\n" +
  331. str(download_video_like_cnt) + "\n" +
  332. str(download_video_share_cnt) + "\n" +
  333. str(download_video_resolution) + "\n" +
  334. str(int(time.mktime(
  335. time.strptime(download_video_send_time, "%Y/%m/%d %H:%M:%S")))) + "\n" +
  336. str(download_user_name) + "\n" +
  337. str(download_head_url) + "\n" +
  338. str(download_video_url) + "\n" +
  339. str(download_cover_url) + "\n" +
  340. str(cls.wesee_access_token))
  341. Common.logger("follow").info("==========视频信息已保存至info.txt==========")
  342. # 上传视频
  343. Common.logger("follow").info("开始上传视频:{}".format(download_video_title))
  344. Publish.upload_and_publish("follow", "prod", "play")
  345. # 保存视频 ID 到云文档:https://w42nne6hzg.feishu.cn/sheets/shtcn5YSWg91JfVGzj0SFZIRRPh?sheet=caa3fa
  346. Common.logger("follow").info("保存视频ID至云文档:{}", download_video_title)
  347. # 视频ID工作表,插入首行
  348. Feishu.insert_columns("follow", "caa3fa", "ROWS", 1, 2)
  349. # 视频ID工作表,首行写入数据
  350. upload_time = int(time.time())
  351. values = [[str(time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time))),
  352. "关注榜",
  353. str(download_video_id),
  354. str(download_video_title),
  355. download_video_play_cnt,
  356. download_video_comment_cnt,
  357. download_video_like_cnt,
  358. download_video_share_cnt,
  359. download_video_duration,
  360. str(download_video_resolution),
  361. str(download_video_send_time),
  362. str(download_user_name),
  363. str(download_user_id),
  364. str(download_head_url),
  365. str(download_cover_url),
  366. str(download_video_url)]]
  367. time.sleep(1)
  368. Feishu.update_values("follow", "caa3fa", "A2:Q2", values)
  369. # 删除行或列,可选 ROWS、COLUMNS
  370. Feishu.dimension_range("follow", "PamIy1", "ROWS", i + 1, i + 1)
  371. return
  372. except Exception as e:
  373. Common.logger("follow").error("下载/上传视频异常:{}", e)
  374. Feishu.dimension_range("follow", "PamIy1", "ROWS", 2, 2)
  375. if __name__ == "__main__":
  376. download_follow = DownloadFollow()
  377. download_follow.get_feeds()
  378. download_follow.download_publish()