download_kuaishou.py 24 KB

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