download_kuaishou.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/3/29
  4. """
  5. 从 微信小程序-快手短视频 中,下载符合规则的视频
  6. """
  7. import json
  8. import time
  9. import requests
  10. import urllib3
  11. from main.common import Common
  12. from main.publish import Publish
  13. class KuaiShou:
  14. # 已下载视频列表
  15. download_video_list = []
  16. @classmethod
  17. def kuaishou_sensitive_words(cls):
  18. sensitive_words = [
  19. "集结吧光合创作者",
  20. "电影解说",
  21. "快来露两手",
  22. "分享家常美食教程",
  23. "光合作者助手",
  24. "创作者中心",
  25. "创作者学院",
  26. "娱乐星熠计划",
  27. "解说电影",
  28. "电影剪辑",
  29. "放映室",
  30. "老剧",
  31. "影视剪辑",
  32. "精彩片段",
  33. "冬日影娱大作战",
  34. "春日追剧计划单",
  35. "影视解说",
  36. "中视频影视混剪计划",
  37. "众志成城共抗疫情",
  38. "我在追好剧",
  39. "娱乐星灿计划",
  40. "电影",
  41. "电视剧",
  42. "毛泽东",
  43. "毛主席",
  44. "周恩来",
  45. "林彪",
  46. "习近平",
  47. "习大大",
  48. "彭丽媛",
  49. "怀旧经典影视",
  50. ]
  51. return sensitive_words
  52. @staticmethod
  53. def kuaishou_download_rule(d_duration, d_width, d_height,
  54. d_play_cnt, d_like_cnt, d_share_cnt):
  55. """
  56. 下载视频的基本规则
  57. :param d_duration: 时长
  58. :param d_width: 宽
  59. :param d_height: 高
  60. :param d_play_cnt: 播放量
  61. :param d_like_cnt: 点赞量
  62. :param d_share_cnt: 分享量
  63. :return: 满足规则,返回 True;反之,返回 False
  64. """
  65. if 600 >= int(float(d_duration)) >= 60:
  66. if int(d_width) >= 720 or int(d_height) >= 720:
  67. if int(d_play_cnt) >= 50000:
  68. if int(d_like_cnt) >= 50000:
  69. if int(d_share_cnt) >= 2000:
  70. return True
  71. else:
  72. return False
  73. else:
  74. return False
  75. else:
  76. return False
  77. return False
  78. return False
  79. @classmethod
  80. def kuaishou_get_recommend(cls):
  81. """
  82. 从快手小程序首页推荐获取视频list:
  83. 1.在 kuaishou_videoid.txt 中去重
  84. 2.在 kuaishou_feeds.txt 中去重
  85. 3.添加视频信息到 kuaishou_feeds.txt
  86. """
  87. url = "https://wxmini-api.uyouqu.com/rest/wd/wechatApp/feed/recommend"
  88. params = {
  89. "__NS_sig3": "e6f6b281ea31e3d7d1bbb8b91f662576fc25f7c3a7a7a5a5aaaba8b2",
  90. "__NS_sig3_origin": "3sCt3iAAAAAAAAAAAAAAAwEQBv2b8ewCwkZKaiAAAAAPg0soi"
  91. "e7GiOlU vF4zPrG1Nl6xvaoBgFd3MwTzOed9w=="
  92. }
  93. cookies = {
  94. "did": "wxo_05f915ac6b1deca87db36cea1a0fd18fae6c",
  95. "preMinaVersion": "v3.109.0",
  96. "sid": "kuaishou.wechat.app",
  97. "appId": "ks_wechat_small_app_2",
  98. "clientid": "13",
  99. "client_key": "f60ac815",
  100. "kpn": "WECHAT_SMALL_APP",
  101. "kpf": "OUTSIDE_ANDROID_H5",
  102. "language": "zh_CN",
  103. "smallAppVersion": "v3.109.0",
  104. "session_key": "123005bcc551a92aac29cdb96190251c9f492c29d4ba6c502dc"
  105. "0d2f8b8d18df356a2f7a22d6924d1dd34b8554a64af49b1bb1a"
  106. "1236cd2f69c25d4ac2a2531ebcd28c179da14b222023f9e111c"
  107. "c4d3b064ac7b0915d8c9fdaccb59e4048e96a5c38a32b2ce9f4abf628053001",
  108. "unionid": "V2:1230b56c8337908c3eecba63142a58daca05535c1f14bf67d3d8"
  109. "85cace91a7db335c5572d204762d075f24aa84412e2955711a12bb9"
  110. "2bd9c2290489ba7a733708a4a446de83822205ab727650489dda0db"
  111. "9d2a226c5ddb66d88a1f1373283a3d3b959611d816660028053001",
  112. "eUserStableOpenId": "12303325e8710eb802137c70fd1fb65997a4e5e33d82"
  113. "cddd409d335d096e20873e07ee472090133bc7a67e5c"
  114. "749da045d9a31a12da4c4c26181d432b873ec39432f4"
  115. "10196c6c2220323d0e6b562d1b3786aefb352b4e509c"
  116. "d96f3466b7b2e5e74b904a94c40792d928053001",
  117. "openId": "o5otV45DcV1EUsWw4fAUk_iq0YSA",
  118. "eOpenUserId": "124074b7726c996283f25044a42e2c7427e929cd6d968c5342"
  119. "330e61fc8939e57b0da4ffe21887f3abc8784175f73e1a267d"
  120. "671247273806f293f64c9c8c2adc00a21a12bb92bd9c229048"
  121. "9ba7a733708a4a446de8382220534aa79c69b74866bb09187e"
  122. "eceec880fa1e0fa421b7df8b3289dab603b17c4828053001",
  123. "kuaishou.wechat.app_st": "ChZrdWFpc2hvdS53ZWNoYXQuYXBwLnN0ErAB8aO"
  124. "EcB6jh4CMSJ-p_4BJFCId0PKNa_5IeFfeV_tj7q"
  125. "CjdXK0y13CSte6-KHbNK9BPo6Rjy3OGny0sh4Zb"
  126. "5AUl3Q_zqVXe2TunW7_F3nlTdJOdZ6iVIhPrHa1"
  127. "CM0Y-cG9gS4FDDzTvejfWaTI0CbjfNN0RZXzYVE"
  128. "AUVT_BNgUVDtYBbEY792gPylMfXxwxKMSzkhaDe"
  129. "eaHkGCWUj62FGCFYQ9Fw2W3d7suCXFsNylqT4aE"
  130. "s8oNwmycUiygfvfKuoXlHkbeSIgOhEFMZ3ArImS"
  131. "vFY_OwLJDHak1iXRO8g5TwzHTvBT3WcoBTAB",
  132. "passToken": "ChNwYXNzcG9ydC5wYXNzLXRva2VuEpABI42IhPCJHfFngXC3i-vF"
  133. "3daRTB-EtnAYyE6HpfWcPoZ6VSRDvKrom_RvltQ2zKk1T3_FJteb"
  134. "mv7ZzQLD7IicnTypaGoeflb7KQVrAv50Mp_JL4ObfBu_xTiwI53t"
  135. "bTlM6iML0G7DFd16K5z0jZZ1xECKVQQbk_vIqnseUujFIWAsKcDz"
  136. "BqqfnQNbUU5DzDUkGhKgKyzmNjRDxLfpDU5SPFhJmG0iIGBZ_Vd-"
  137. "7eT8i_Xit9ZPM-zdFpnRZFveFE9iplMg8Z06KAUwAQ",
  138. "userId": "2845397958"
  139. }
  140. json_data = {
  141. "thirdPartyUserId": 2845397958,
  142. "photoId": "5250352807040393911",
  143. "forwardUserId": 2845397958,
  144. "count": 10,
  145. "portal": 2,
  146. "pageType": 2,
  147. "needLivestream": "true",
  148. "extraRequestInfo": "{\"scene\":1074,\"fid\":\"2845397958\","
  149. "\"sharerUserId\":\"2845397958\",\"curPhotoIndex\":0,"
  150. "\"adShow\":true,\"weChatAd\":{},\"page\":0}",
  151. "pcursor": 0,
  152. "sourceFrom": 2,
  153. }
  154. try:
  155. urllib3.disable_warnings()
  156. r = requests.post(url=url, params=params, cookies=cookies, json=json_data, verify=False)
  157. response = json.loads(r.content.decode("utf8"))
  158. if "feeds" not in response:
  159. Common.crawler_log().info("获取快手视频 list 出错:{},休眠 10s".format(response))
  160. time.sleep(10)
  161. else:
  162. feeds = response["feeds"]
  163. for i in range(len(feeds)):
  164. if "photoId" not in feeds[i]:
  165. photo_id = "0"
  166. Common.crawler_log().info("photo_id:{}".format(photo_id))
  167. else:
  168. photo_id = feeds[i]["photoId"]
  169. Common.crawler_log().info("photo_id:{}".format(photo_id))
  170. if "viewCount" not in feeds[i]:
  171. video_play_cnt = "0"
  172. Common.crawler_log().info("video_play_cnt:0")
  173. else:
  174. video_play_cnt = feeds[i]["viewCount"]
  175. Common.crawler_log().info("video_play_cnt:{}".format(video_play_cnt))
  176. if "likeCount" not in feeds[i]:
  177. video_like_cnt = "0"
  178. Common.crawler_log().info("video_like_cnt:0")
  179. else:
  180. video_like_cnt = feeds[i]["likeCount"]
  181. Common.crawler_log().info("video_like_cnt:{}".format(video_like_cnt))
  182. if "headUrl" not in feeds[i]:
  183. head_url = "0"
  184. Common.crawler_log().info("head_url:不存在")
  185. else:
  186. head_url = feeds[i]["headUrl"]
  187. Common.crawler_log().info("head_url:{}".format(head_url))
  188. if len(feeds[i]["coverUrls"]) == 0:
  189. cover_url = "0"
  190. Common.crawler_log().info("cover_url:不存在")
  191. else:
  192. cover_url = feeds[i]["coverUrls"][0]["url"]
  193. Common.crawler_log().info("cover_url:{}".format(cover_url))
  194. if len(feeds[i]["mainMvUrls"]) == 0:
  195. video_url = "0"
  196. Common.crawler_log().info("video_url:不存在")
  197. else:
  198. video_url = feeds[i]["mainMvUrls"][0]["url"]
  199. Common.crawler_log().info("video_url:{}".format(video_url))
  200. if "shareCount" not in feeds[i]:
  201. video_share_cnt = "0"
  202. Common.crawler_log().info("video_share_cnt:0")
  203. else:
  204. video_share_cnt = feeds[i]["shareCount"]
  205. Common.crawler_log().info("video_share_cnt:{}".format(video_share_cnt))
  206. if "width" not in feeds[i] or "height"not in feeds[i]:
  207. video_width = "0"
  208. video_height = "0"
  209. video_resolution = str(video_width) + "*" + str(video_height)
  210. Common.crawler_log().info("无分辨率")
  211. else:
  212. video_width = feeds[i]["width"]
  213. video_height = feeds[i]["height"]
  214. video_resolution = str(video_width) + "*" + str(video_height)
  215. Common.crawler_log().info("video_resolution:{}".format(video_resolution))
  216. if "commentCount" not in feeds[i]:
  217. video_comment_cnt = "0"
  218. Common.crawler_log().info("video_comment_cnt:0")
  219. else:
  220. video_comment_cnt = feeds[i]["commentCount"]
  221. Common.crawler_log().info("video_comment_cnt:{}".format(video_comment_cnt))
  222. if "duration" not in feeds[i]:
  223. video_duration = "0"
  224. Common.crawler_log().info("video_duration:不存在")
  225. else:
  226. video_duration = int(int(feeds[i]["duration"])/1000)
  227. Common.crawler_log().info("video_duration:{}秒".format(video_duration))
  228. if "timestamp" not in feeds[i]:
  229. video_send_time = "0"
  230. Common.crawler_log().info("video_send_time:不存在")
  231. else:
  232. video_send_time = feeds[i]["timestamp"]
  233. Common.crawler_log().info("video_send_time:{}".format(
  234. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(video_send_time)/1000))))
  235. user_name = feeds[i]["userName"].strip().replace("\n", "")\
  236. .replace("/", "").replace("快手", "").replace(" ", "")\
  237. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  238. Common.crawler_log().info("user_name:{}".format(user_name))
  239. user_id = feeds[i]["userId"]
  240. Common.crawler_log().info("user_id:{}".format(user_id))
  241. # 视频标题过滤话题及处理特殊字符
  242. kuaishou_title = feeds[i]["caption"]
  243. title_split1 = kuaishou_title.split(" #")
  244. if title_split1[0] != "":
  245. title1 = title_split1[0]
  246. else:
  247. title1 = title_split1[-1]
  248. title_split2 = title1.split(" #")
  249. if title_split2[0] != "":
  250. title2 = title_split2[0]
  251. else:
  252. title2 = title_split2[-1]
  253. title_split3 = title2.split("@")
  254. if title_split3[0] != "":
  255. title3 = title_split3[0]
  256. else:
  257. title3 = title_split3[-1]
  258. video_title = title3.strip().replace("\n", "")\
  259. .replace("/", "").replace("快手", "").replace(" ", "")\
  260. .replace(" ", "").replace("&NBSP", "").replace("\r", "")\
  261. .replace("#", "").replace(".", "。")
  262. Common.crawler_log().info("video_title:{}".format(video_title))
  263. # 从 kuaishou_videoid.txt 中去重
  264. photo_ids = Common.read_txt("kuaishou_videoid.txt")
  265. if photo_id in [p_id.strip() for p_id in photo_ids]:
  266. Common.crawler_log().info("该视频已下载:{}".format(video_title))
  267. pass
  268. else:
  269. Common.crawler_log().info("该视频未下载:{}".format(video_title))
  270. # 从 kuaishou_feeds.txt 中去重
  271. contents = Common.read_txt("kuaishou_feeds.txt")
  272. # kuaishou_feeds.txt 为空时,直接保存
  273. if len(contents) == 0 and head_url != "0" \
  274. and cover_url != "0" and video_url != "0" \
  275. and video_duration != "0" and photo_id != "0":
  276. # 判断敏感词
  277. if any(word if word in kuaishou_title else False
  278. for word in cls.kuaishou_sensitive_words()) is True:
  279. Common.crawler_log().info("视频已中敏感词:{}".format(kuaishou_title))
  280. else:
  281. basic_time = int(time.time())
  282. Common.crawler_log().info("添加视频信息至kuaishou_feeds.txt:{}".format(video_title))
  283. with open("./txt/kuaishou_feeds.txt", "a", encoding="utf8") as f_a:
  284. f_a.write(str(basic_time) + " + " +
  285. str(photo_id) + " + " +
  286. str(video_play_cnt) + " + " +
  287. str(video_title) + " + " +
  288. str(video_duration) + " + " +
  289. str(video_comment_cnt) + " + " +
  290. str(video_like_cnt) + " + " +
  291. str(video_share_cnt) + " + " +
  292. str(video_resolution) + " + " +
  293. str(video_send_time) + " + " +
  294. str(user_name) + " + " +
  295. str(head_url) + " + " +
  296. str(cover_url) + " + " +
  297. str(video_url) + " + " +
  298. str(user_id) + " + " +
  299. str("wxo_b07ba02ad4340205d89b47c76030bb090977") + "\n")
  300. else:
  301. if photo_id in [content.split(" + ")[1] for content in contents]:
  302. Common.crawler_log().info("该视频已在 kuaishou_feeds.txt 中:{}".format(video_title))
  303. elif head_url == "0" or cover_url == "0" \
  304. or video_url == "0" or video_duration == "0" or photo_id == "0":
  305. Common.crawler_log().info("视频封面/播放地址/播放时长/用户头像不存在")
  306. else:
  307. # 判断敏感词
  308. if any(word if word in kuaishou_title else False
  309. for word in cls.kuaishou_sensitive_words()) is True:
  310. Common.crawler_log().info("视频已中敏感词:{}".format(kuaishou_title))
  311. else:
  312. basic_time = int(time.time())
  313. Common.crawler_log().info("添加视频信息至kuaishou_feeds.txt:{}".format(video_title))
  314. with open("./txt/kuaishou_feeds.txt", "a", encoding="utf8") as f_a:
  315. f_a.write(str(basic_time) + " + " +
  316. str(photo_id) + " + " +
  317. str(video_play_cnt) + " + " +
  318. str(video_title) + " + " +
  319. str(video_duration) + " + " +
  320. str(video_comment_cnt) + " + " +
  321. str(video_like_cnt) + " + " +
  322. str(video_share_cnt) + " + " +
  323. str(video_resolution) + " + " +
  324. str(video_send_time) + " + " +
  325. str(user_name) + " + " +
  326. str(head_url) + " + " +
  327. str(cover_url) + " + " +
  328. str(video_url) + " + " +
  329. str(user_id) + " + " +
  330. str("wxo_b07ba02ad4340205d89b47c76030bb090977") + "\n")
  331. except Exception as e:
  332. Common.crawler_log().error("获取视频 list 异常:{}".format(e))
  333. @classmethod
  334. def kuaishou_download_play_video(cls, env):
  335. """
  336. 下载播放量视频
  337. 测试环境:env == dev
  338. 正式环境:env == prod
  339. """
  340. videos = Common.read_txt("kuaishou_feeds.txt")
  341. for video in videos:
  342. download_photo_id = video.strip().split(" + ")[1]
  343. download_video_title = video.strip().split(" + ")[3]
  344. download_video_duration = video.strip().split(" + ")[4]
  345. download_video_play_cnt = video.strip().split(" + ")[2]
  346. download_video_comment_cnt = video.strip().split(" + ")[5]
  347. download_video_like_cnt = video.strip().split(" + ")[6]
  348. download_video_share_cnt = video.strip().split(" + ")[7]
  349. download_video_resolution = video.strip().split(" + ")[8]
  350. download_video_width = download_video_resolution.split("*")[0]
  351. download_video_height = download_video_resolution.split("*")[-1]
  352. download_video_send_time = video.strip().split(" + ")[9]
  353. download_user_name = video.strip().split(" + ")[10]
  354. download_head_url = video.strip().split(" + ")[11]
  355. download_cover_url = video.strip().split(" + ")[12]
  356. download_video_url = video.strip().split(" + ")[13]
  357. download_video_session = video.strip().split(" + ")[-1]
  358. if cls.kuaishou_download_rule(download_video_duration,
  359. download_video_width,
  360. download_video_height,
  361. download_video_play_cnt,
  362. download_video_like_cnt,
  363. download_video_share_cnt) is True:
  364. Common.crawler_log().info("开始下载快手视频:{}".format(download_video_title))
  365. # 下载封面
  366. Common.download_method(text="cover", d_name=download_video_title, d_url=download_cover_url)
  367. # 下载视频
  368. Common.download_method(text="video", d_name=download_video_title, d_url=download_video_url)
  369. # 保存视频信息至 kuaishou_videoid.txt
  370. with open("./txt/kuaishou_videoid.txt", "a", encoding="utf8") as fa:
  371. fa.write(download_photo_id + "\n")
  372. # 添加视频 ID 到 list,用于统计当次下载总数
  373. cls.download_video_list.append(download_photo_id)
  374. # # 保存视频信息至 {today}_kuaishou_videoid.txt
  375. # with open("./txt/" + str(Common.today) + "_kuaishou_videoid.txt", "a", encoding="utf8") as fc:
  376. # fc.write(download_photo_id + "\n")
  377. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  378. with open("./videos/" + download_video_title + "/info.txt", "a", encoding="utf8") as f_a:
  379. f_a.write(str(download_photo_id) + "\n" +
  380. str(download_video_title) + "\n" +
  381. str(download_video_duration) + "\n" +
  382. str(download_video_play_cnt) + "\n" +
  383. str(download_video_comment_cnt) + "\n" +
  384. str(download_video_like_cnt) + "\n" +
  385. str(download_video_share_cnt) + "\n" +
  386. str(download_video_resolution) + "\n" +
  387. str(download_video_send_time) + "\n" +
  388. str(download_user_name) + "\n" +
  389. str(download_head_url) + "\n" +
  390. str(download_video_url) + "\n" +
  391. str(download_cover_url) + "\n" +
  392. str(download_video_session))
  393. # 上传视频
  394. if env == "dev":
  395. Common.crawler_log().info("开始上传视频:{}".format(download_video_title))
  396. Publish.upload_and_publish("dev", "play")
  397. elif env == "prod":
  398. Common.crawler_log().info("开始上传视频:{}".format(download_video_title))
  399. Publish.upload_and_publish("prod", "play")
  400. # 删除该视频在kuaishou_feeds.txt中的信息
  401. Common.crawler_log().info("删除该视频在kuaishou_feeds.txt中的信息:{}".format(download_video_title))
  402. with open("./txt/kuaishou_feeds.txt", "r", encoding="utf8") as f_r:
  403. lines = f_r.readlines()
  404. with open("./txt/kuaishou_feeds.txt", "w", encoding="utf-8") as f_w:
  405. for line in lines:
  406. if download_photo_id in line.split(" + ")[1]:
  407. continue
  408. f_w.write(line)
  409. else:
  410. # 删除该视频在 recommend.txt中的信息
  411. Common.crawler_log().info("该视频不满足下载规则,删除在kuaishou_feeds.txt中的信息:{}".format(download_video_title))
  412. with open("./txt/kuaishou_feeds.txt", "r", encoding="utf8") as f_r:
  413. lines = f_r.readlines()
  414. with open("./txt/kuaishou_feeds.txt", "w", encoding="utf-8") as f_w:
  415. for line in lines:
  416. if download_photo_id in line.split(" + ")[1]:
  417. continue
  418. f_w.write(line)
  419. if __name__ == "__main__":
  420. kuaishou = KuaiShou()
  421. kuaishou.kuaishou_get_recommend()