kuaishou_follow.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/2/24
  4. import os
  5. import random
  6. import shutil
  7. import sys
  8. import time
  9. from hashlib import md5
  10. import requests
  11. import json
  12. import urllib3
  13. from requests.adapters import HTTPAdapter
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common.feishu import Feishu
  17. from common.getuser import getUser
  18. from common.db import MysqlHelper
  19. from common.publish import Publish
  20. from common.public import get_user_from_mysql
  21. from common.userAgent import get_random_user_agent
  22. class KuaiShouFollow:
  23. platform = "快手"
  24. tag = "快手爬虫,定向爬虫策略"
  25. @classmethod
  26. def get_rule(cls, log_type, crawler, index):
  27. try:
  28. rule_sheet = Feishu.get_values_batch(log_type, crawler, "3iqG4z")
  29. if index == 1:
  30. rule_dict = {
  31. "play_cnt": f"{rule_sheet[1][1]}{rule_sheet[1][2]}",
  32. "video_width": f"{rule_sheet[2][1]}{rule_sheet[2][2]}",
  33. "video_height": f"{rule_sheet[3][1]}{rule_sheet[3][2]}",
  34. "like_cnt": f"{rule_sheet[4][1]}{rule_sheet[4][2]}",
  35. "duration": f"{rule_sheet[5][1]}{rule_sheet[5][2]}",
  36. "download_cnt": f"{rule_sheet[6][1]}{rule_sheet[6][2]}",
  37. "publish_time": f"{rule_sheet[7][1]}{rule_sheet[7][2]}",
  38. }
  39. # for k, v in rule_dict.items():
  40. # Common.logger(log_type, crawler).info(f"{k}:{v}")
  41. return rule_dict
  42. elif index == 2:
  43. rule_dict = {
  44. "play_cnt": f"{rule_sheet[9][1]}{rule_sheet[9][2]}",
  45. "video_width": f"{rule_sheet[10][1]}{rule_sheet[10][2]}",
  46. "video_height": f"{rule_sheet[11][1]}{rule_sheet[11][2]}",
  47. "like_cnt": f"{rule_sheet[12][1]}{rule_sheet[12][2]}",
  48. "duration": f"{rule_sheet[13][1]}{rule_sheet[13][2]}",
  49. "download_cnt": f"{rule_sheet[14][1]}{rule_sheet[14][2]}",
  50. "publish_time": f"{rule_sheet[15][1]}{rule_sheet[15][2]}",
  51. }
  52. # for k, v in rule_dict.items():
  53. # Common.logger(log_type, crawler).info(f"{k}:{v}")
  54. return rule_dict
  55. except Exception as e:
  56. Common.logger(log_type, crawler).error(f"get_rule:{e}\n")
  57. @classmethod
  58. def download_rule(cls, video_dict, rule_dict):
  59. if eval(f"{video_dict['play_cnt']}{rule_dict['play_cnt']}") is True \
  60. and eval(f"{video_dict['video_width']}{rule_dict['video_width']}") is True \
  61. and eval(f"{video_dict['video_height']}{rule_dict['video_height']}") is True \
  62. and eval(f"{video_dict['like_cnt']}{rule_dict['like_cnt']}") is True \
  63. and eval(f"{video_dict['duration']}{rule_dict['duration']}") is True \
  64. and eval(f"{video_dict['publish_time']}{rule_dict['publish_time']}") is True:
  65. return True
  66. else:
  67. return False
  68. # 过滤词库
  69. @classmethod
  70. def filter_words(cls, log_type, crawler):
  71. try:
  72. while True:
  73. filter_words_sheet = Feishu.get_values_batch(log_type, crawler, 'HIKVvs')
  74. if filter_words_sheet is None:
  75. Common.logger(log_type, crawler).warning(f"filter_words_sheet:{filter_words_sheet} 10秒钟后重试")
  76. continue
  77. filter_words_list = []
  78. for x in filter_words_sheet:
  79. for y in x:
  80. if y is None:
  81. pass
  82. else:
  83. filter_words_list.append(y)
  84. return filter_words_list
  85. except Exception as e:
  86. Common.logger(log_type, crawler).error(f'filter_words异常:{e}\n')
  87. # 万能标题
  88. @classmethod
  89. def random_title(cls, log_type, crawler):
  90. try:
  91. while True:
  92. random_title_sheet = Feishu.get_values_batch(log_type, crawler, '0DiyXe')
  93. if random_title_sheet is None:
  94. Common.logger(log_type, crawler).warning(f"filter_words_sheet:{random_title_sheet} 10秒钟后重试")
  95. continue
  96. random_title_list = []
  97. for x in random_title_sheet:
  98. for y in x:
  99. if y is None:
  100. pass
  101. else:
  102. random_title_list.append(y)
  103. return random.choice(random_title_list)
  104. except Exception as e:
  105. Common.logger(log_type, crawler).error(f'random_title:{e}\n')
  106. # 获取站外用户信息
  107. @classmethod
  108. def get_out_user_info(cls, log_type, crawler, out_uid):
  109. try:
  110. url = "https://www.kuaishou.com/graphql"
  111. payload = json.dumps({
  112. "operationName": "visionProfile",
  113. "variables": {
  114. "userId": out_uid
  115. },
  116. "query": "query visionProfile($userId: String) {\n visionProfile(userId: $userId) {\n result\n hostName\n userProfile {\n ownerCount {\n fan\n photo\n follow\n photo_public\n __typename\n }\n profile {\n gender\n user_name\n user_id\n headurl\n user_text\n user_profile_bg_url\n __typename\n }\n isFollowing\n __typename\n }\n __typename\n }\n}\n"
  117. })
  118. headers = {
  119. 'Accept': '*/*',
  120. 'Content-Type': 'application/json',
  121. 'Origin': 'https://www.kuaishou.com',
  122. 'Cookie': 'did=web_cb989442745f6db4521d6b21032475a6;; clientid=3; kpf=PC_WEB; kpn=KUAISHOU_VISION',
  123. 'Content-Length': '552',
  124. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  125. 'Host': 'www.kuaishou.com',
  126. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15',
  127. 'Referer': 'https://www.kuaishou.com/profile/{}'.format(out_uid),
  128. 'Accept-Encoding': 'gzip, deflate, br',
  129. 'Connection': 'keep-alive'
  130. }
  131. urllib3.disable_warnings()
  132. s = requests.session()
  133. # max_retries=3 重试3次
  134. s.mount('http://', HTTPAdapter(max_retries=3))
  135. s.mount('https://', HTTPAdapter(max_retries=3))
  136. response = s.post(url=url, headers=headers, data=payload, proxies=Common.tunnel_proxies(), verify=False,
  137. timeout=5)
  138. response.close()
  139. # Common.logger(log_type, crawler).info(f"get_out_user_info_response:{response.text}")
  140. if response.status_code != 200:
  141. Common.logger(log_type, crawler).warning(f"get_out_user_info_response:{response.text}\n")
  142. return
  143. elif 'data' not in response.json():
  144. Common.logger(log_type, crawler).warning(f"get_out_user_info_response:{response.json()}\n")
  145. return
  146. elif 'visionProfile' not in response.json()['data']:
  147. Common.logger(log_type, crawler).warning(f"get_out_user_info_response:{response.json()['data']}\n")
  148. return
  149. elif 'userProfile' not in response.json()['data']['visionProfile']:
  150. Common.logger(log_type, crawler).warning(
  151. f"get_out_user_info_response:{response.json()['data']['visionProfile']['userProfile']}\n")
  152. return
  153. else:
  154. userProfile = response.json()['data']['visionProfile']['userProfile']
  155. # Common.logger(log_type, crawler).info(f"userProfile:{userProfile}")
  156. try:
  157. out_fans_str = str(userProfile['ownerCount']['fan'])
  158. except Exception:
  159. out_fans_str = "0"
  160. try:
  161. out_follow_str = str(userProfile['ownerCount']['follow'])
  162. except Exception:
  163. out_follow_str = "0"
  164. try:
  165. out_avatar_url = userProfile['profile']['headurl']
  166. except Exception:
  167. out_avatar_url = ""
  168. Common.logger(log_type, crawler).info(f"out_fans_str:{out_fans_str}")
  169. Common.logger(log_type, crawler).info(f"out_follow_str:{out_follow_str}")
  170. Common.logger(log_type, crawler).info(f"out_avatar_url:{out_avatar_url}")
  171. if "万" in out_fans_str:
  172. out_fans = int(float(out_fans_str.split("万")[0]) * 10000)
  173. else:
  174. out_fans = int(out_fans_str.replace(",", ""))
  175. if "万" in out_follow_str:
  176. out_follow = int(float(out_follow_str.split("万")[0]) * 10000)
  177. else:
  178. out_follow = int(out_follow_str.replace(",", ""))
  179. out_user_dict = {
  180. "out_fans": out_fans,
  181. "out_follow": out_follow,
  182. "out_avatar_url": out_avatar_url
  183. }
  184. Common.logger(log_type, crawler).info(f"out_user_dict:{out_user_dict}")
  185. return out_user_dict
  186. except Exception as e:
  187. Common.logger(log_type, crawler).error(f"get_out_user_info:{e}\n")
  188. # 获取用户信息列表
  189. @classmethod
  190. def get_user_list(cls, log_type, crawler, sheetid, env, machine):
  191. try:
  192. while True:
  193. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  194. if user_sheet is None:
  195. Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet} 10秒钟后重试")
  196. continue
  197. our_user_list = []
  198. for i in range(1, len(user_sheet)):
  199. # for i in range(1, 2):
  200. out_uid = user_sheet[i][2]
  201. user_name = user_sheet[i][3]
  202. our_uid = user_sheet[i][6]
  203. our_user_link = user_sheet[i][7]
  204. if out_uid is None or user_name is None:
  205. Common.logger(log_type, crawler).info("空行\n")
  206. else:
  207. Common.logger(log_type, crawler).info(f"正在更新 {user_name} 用户信息\n")
  208. if our_uid is None:
  209. out_user_info = cls.get_out_user_info(log_type, crawler, out_uid)
  210. out_user_dict = {
  211. "out_uid": out_uid,
  212. "user_name": user_name,
  213. "out_avatar_url": out_user_info["out_avatar_url"],
  214. "out_create_time": '',
  215. "out_tag": '',
  216. "out_play_cnt": 0,
  217. "out_fans": out_user_info["out_fans"],
  218. "out_follow": out_user_info["out_follow"],
  219. "out_friend": 0,
  220. "out_like": 0,
  221. "platform": cls.platform,
  222. "tag": cls.tag,
  223. }
  224. our_user_dict = getUser.create_user(log_type=log_type, crawler=crawler,
  225. out_user_dict=out_user_dict, env=env, machine=machine)
  226. our_uid = our_user_dict['our_uid']
  227. our_user_link = our_user_dict['our_user_link']
  228. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}',
  229. [[our_uid, our_user_link]])
  230. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!\n')
  231. our_user_list.append(our_user_dict)
  232. else:
  233. our_user_dict = {
  234. 'out_uid': out_uid,
  235. 'user_name': user_name,
  236. 'our_uid': our_uid,
  237. 'our_user_link': our_user_link,
  238. }
  239. our_user_list.append(our_user_dict)
  240. return our_user_list
  241. except Exception as e:
  242. Common.logger(log_type, crawler).error(f'get_user_list:{e}\n')
  243. # 处理视频标题
  244. @classmethod
  245. def video_title(cls, log_type, crawler, title):
  246. title_split1 = title.split(" #")
  247. if title_split1[0] != "":
  248. title1 = title_split1[0]
  249. else:
  250. title1 = title_split1[-1]
  251. title_split2 = title1.split(" #")
  252. if title_split2[0] != "":
  253. title2 = title_split2[0]
  254. else:
  255. title2 = title_split2[-1]
  256. title_split3 = title2.split("@")
  257. if title_split3[0] != "":
  258. title3 = title_split3[0]
  259. else:
  260. title3 = title_split3[-1]
  261. video_title = title3.strip().replace("\n", "") \
  262. .replace("/", "").replace("快手", "").replace(" ", "") \
  263. .replace(" ", "").replace("&NBSP", "").replace("\r", "") \
  264. .replace("#", "").replace(".", "。").replace("\\", "") \
  265. .replace(":", "").replace("*", "").replace("?", "") \
  266. .replace("?", "").replace('"', "").replace("<", "") \
  267. .replace(">", "").replace("|", "").replace("@", "").replace('"', '').replace("'", '')[:40]
  268. if video_title.replace(" ", "") == "" or video_title == "。。。" or video_title == "...":
  269. return cls.random_title(log_type, crawler)
  270. else:
  271. return video_title
  272. @classmethod
  273. def get_videoList(cls, log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine, pcursor=""):
  274. download_cnt_1, download_cnt_2 = 0, 0
  275. rule_dict_1 = cls.get_rule(log_type, crawler, 1)
  276. rule_dict_2 = cls.get_rule(log_type, crawler, 2)
  277. if rule_dict_1 is None or rule_dict_2 is None:
  278. Common.logger(log_type, crawler).warning(f"rule_dict is None")
  279. return
  280. url = "https://www.kuaishou.com/graphql"
  281. payload = json.dumps({
  282. "operationName": "visionProfilePhotoList",
  283. "variables": {
  284. "userId": out_uid,
  285. "pcursor": "",
  286. "page": "profile"
  287. },
  288. "query": "fragment photoContent on PhotoEntity {\n id\n duration\n caption\n originCaption\n likeCount\n viewCount\n commentCount\n realLikeCount\n coverUrl\n photoUrl\n photoH265Url\n manifest\n manifestH265\n videoResource\n coverUrls {\n url\n __typename\n }\n timestamp\n expTag\n animatedCoverUrl\n distance\n videoRatio\n liked\n stereoType\n profileUserTopPhoto\n musicBlocked\n __typename\n}\n\nfragment feedContent on Feed {\n type\n author {\n id\n name\n headerUrl\n following\n headerUrls {\n url\n __typename\n }\n __typename\n }\n photo {\n ...photoContent\n __typename\n }\n canAddComment\n llsid\n status\n currentPcursor\n tags {\n type\n name\n __typename\n }\n __typename\n}\n\nquery visionProfilePhotoList($pcursor: String, $userId: String, $page: String, $webPageArea: String) {\n visionProfilePhotoList(pcursor: $pcursor, userId: $userId, page: $page, webPageArea: $webPageArea) {\n result\n llsid\n webPageArea\n feeds {\n ...feedContent\n __typename\n }\n hostName\n pcursor\n __typename\n }\n}\n"
  289. })
  290. headers = {
  291. 'Accept': '*/*',
  292. 'Content-Type': 'application/json',
  293. 'Origin': 'https://www.kuaishou.com',
  294. 'Cookie': 'did=web_cc76bddba88f7634e173c5baf7fb586b; clientid=3; kpf=PC_WEB; kpn=KUAISHOU_VISION; did=web_5d4d0dff78b7819f8b015e7a81e2ca98; clientid=3; kpf=PC_WEB; kpn=KUAISHOU_VISION',
  295. 'Content-Length': '1260',
  296. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  297. 'Host': 'www.kuaishou.com',
  298. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6.1 Safari/605.1.15',
  299. 'Referer': 'https://www.kuaishou.com/profile/{}'.format(out_uid),
  300. 'Accept-Encoding': 'gzip, deflate, br',
  301. 'Connection': 'keep-alive'
  302. }
  303. try:
  304. response = requests.post(url=url, headers=headers, data=payload, proxies=Common.tunnel_proxies(),
  305. verify=False, timeout=10)
  306. except Exception as e:
  307. Common.logger(log_type, crawler).error(f"get_videoList:{e}\n")
  308. return
  309. # Common.logger(log_type, crawler).info(f"get_videoList:{response.text}\n")
  310. if response.status_code != 200:
  311. Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.text}\n")
  312. return
  313. elif 'data' not in response.json():
  314. Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()}\n")
  315. return
  316. elif 'visionProfilePhotoList' not in response.json()['data']:
  317. Common.logger(log_type, crawler).warning(f"get_videoList_response:{response.json()['data']}\n")
  318. return
  319. elif 'feeds' not in response.json()['data']['visionProfilePhotoList']:
  320. Common.logger(log_type, crawler).warning(
  321. f"get_videoList_response:{response.json()['data']['visionProfilePhotoList']}\n")
  322. return
  323. elif len(response.json()['data']['visionProfilePhotoList']['feeds']) == 0:
  324. Common.logger(log_type, crawler).info("没有更多视频啦 ~\n")
  325. return
  326. else:
  327. feeds = response.json()['data']['visionProfilePhotoList']['feeds']
  328. pcursor = response.json()['data']['visionProfilePhotoList']['pcursor']
  329. # Common.logger(log_type, crawler).info(f"feeds0: {feeds}\n")
  330. for i in range(len(feeds)):
  331. if 'photo' not in feeds[i]:
  332. Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]}\n")
  333. break
  334. # video_title
  335. if 'caption' not in feeds[i]['photo']:
  336. video_title = cls.random_title(log_type, crawler)
  337. elif feeds[i]['photo']['caption'].strip() == "":
  338. video_title = cls.random_title(log_type, crawler)
  339. else:
  340. video_title = cls.video_title(log_type, crawler, feeds[i]['photo']['caption'])
  341. if 'videoResource' not in feeds[i]['photo'] \
  342. and 'manifest' not in feeds[i]['photo'] \
  343. and 'manifestH265' not in feeds[i]['photo']:
  344. Common.logger(log_type, crawler).warning(f"get_videoList:{feeds[i]['photo']}\n")
  345. break
  346. videoResource = feeds[i]['photo']['videoResource']
  347. if 'h264' not in videoResource and 'hevc' not in videoResource:
  348. Common.logger(log_type, crawler).warning(f"get_videoList:{videoResource}\n")
  349. break
  350. # video_id
  351. if 'h264' in videoResource and 'videoId' in videoResource['h264']:
  352. video_id = videoResource['h264']['videoId']
  353. elif 'hevc' in videoResource and 'videoId' in videoResource['hevc']:
  354. video_id = videoResource['hevc']['videoId']
  355. else:
  356. video_id = ""
  357. # play_cnt
  358. if 'viewCount' not in feeds[i]['photo']:
  359. play_cnt = 0
  360. else:
  361. play_cnt = int(feeds[i]['photo']['viewCount'])
  362. # like_cnt
  363. if 'realLikeCount' not in feeds[i]['photo']:
  364. like_cnt = 0
  365. else:
  366. like_cnt = feeds[i]['photo']['realLikeCount']
  367. # publish_time
  368. if 'timestamp' not in feeds[i]['photo']:
  369. publish_time_stamp = 0
  370. publish_time_str = ''
  371. publish_time = 0
  372. else:
  373. publish_time_stamp = int(int(feeds[i]['photo']['timestamp']) / 1000)
  374. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  375. publish_time = int((int(time.time()) - publish_time_stamp) / (3600 * 24))
  376. # duration
  377. if 'duration' not in feeds[i]['photo']:
  378. duration = 0
  379. else:
  380. duration = int(int(feeds[i]['photo']['duration']) / 1000)
  381. # video_width / video_height / video_url
  382. mapping = {}
  383. for item in ['width', 'height']:
  384. try:
  385. val = str(videoResource['h264']['adaptationSet'][0]['representation'][0][item])
  386. except Exception:
  387. val = str(videoResource['hevc']['adaptationSet'][0]['representation'][0][item])
  388. except:
  389. val = ''
  390. mapping[item] = val
  391. video_width = int(mapping['width']) if mapping['width'] != '' else 0
  392. video_height = int(mapping['height']) if mapping['height'] != '' else 0
  393. # cover_url
  394. if 'coverUrl' not in feeds[i]['photo']:
  395. cover_url = ""
  396. else:
  397. cover_url = feeds[i]['photo']['coverUrl']
  398. # user_name / avatar_url
  399. try:
  400. user_name = feeds[i]['author']['name']
  401. avatar_url = feeds[i]['author']['headerUrl']
  402. except Exception:
  403. user_name = ''
  404. avatar_url = ''
  405. video_url = feeds[i]['photo']['photoUrl']
  406. video_dict = {'video_title': video_title,
  407. 'video_id': video_id,
  408. 'play_cnt': play_cnt,
  409. 'comment_cnt': 0,
  410. 'like_cnt': like_cnt,
  411. 'share_cnt': 0,
  412. 'video_width': video_width,
  413. 'video_height': video_height,
  414. 'duration': duration,
  415. 'publish_time': publish_time,
  416. 'publish_time_stamp': publish_time_stamp,
  417. 'publish_time_str': publish_time_str,
  418. 'user_name': user_name,
  419. 'user_id': out_uid,
  420. 'avatar_url': avatar_url,
  421. 'cover_url': cover_url,
  422. 'video_url': video_url,
  423. 'session': f"kuaishou{int(time.time())}"}
  424. rule_1 = cls.download_rule(video_dict, rule_dict_1)
  425. Common.logger(log_type, crawler).info(f"video_title:{video_title}")
  426. Common.logger(log_type, crawler).info(f"video_id:{video_id}\n")
  427. Common.logger(log_type, crawler).info(
  428. f"play_cnt:{video_dict['play_cnt']}{rule_dict_1['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_1['play_cnt']))}")
  429. Common.logger(log_type, crawler).info(
  430. f"like_cnt:{video_dict['like_cnt']}{rule_dict_1['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_1['like_cnt']))}")
  431. Common.logger(log_type, crawler).info(
  432. f"video_width:{video_dict['video_width']}{rule_dict_1['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_1['video_width']))}")
  433. Common.logger(log_type, crawler).info(
  434. f"video_height:{video_dict['video_height']}{rule_dict_1['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_1['video_height']))}")
  435. Common.logger(log_type, crawler).info(
  436. f"duration:{video_dict['duration']}{rule_dict_1['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_1['duration']))}")
  437. Common.logger(log_type, crawler).info(
  438. f"publish_time:{video_dict['publish_time']}{rule_dict_1['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_1['publish_time']))}")
  439. Common.logger(log_type, crawler).info(f"rule_1:{rule_1}\n")
  440. rule_2 = cls.download_rule(video_dict, rule_dict_2)
  441. Common.logger(log_type, crawler).info(
  442. f"play_cnt:{video_dict['play_cnt']}{rule_dict_2['play_cnt']}, {eval(str(video_dict['play_cnt']) + str(rule_dict_2['play_cnt']))}")
  443. Common.logger(log_type, crawler).info(
  444. f"like_cnt:{video_dict['like_cnt']}{rule_dict_2['like_cnt']}, {eval(str(video_dict['like_cnt']) + str(rule_dict_2['like_cnt']))}")
  445. Common.logger(log_type, crawler).info(
  446. f"video_width:{video_dict['video_width']}{rule_dict_2['video_width']}, {eval(str(video_dict['video_width']) + str(rule_dict_2['video_width']))}")
  447. Common.logger(log_type, crawler).info(
  448. f"video_height:{video_dict['video_height']}{rule_dict_2['video_height']}, {eval(str(video_dict['video_height']) + str(rule_dict_2['video_height']))}")
  449. Common.logger(log_type, crawler).info(
  450. f"duration:{video_dict['duration']}{rule_dict_2['duration']}, {eval(str(video_dict['duration']) + str(rule_dict_2['duration']))}")
  451. Common.logger(log_type, crawler).info(
  452. f"publish_time:{video_dict['publish_time']}{rule_dict_2['publish_time']}, {eval(str(video_dict['publish_time']) + str(rule_dict_2['publish_time']))}")
  453. Common.logger(log_type, crawler).info(f"rule_2:{rule_2}\n")
  454. if video_title == "" or video_url == "":
  455. Common.logger(log_type, crawler).info("无效视频\n")
  456. continue
  457. elif rule_1 is True:
  458. if download_cnt_1 < int(
  459. rule_dict_1['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
  460. "")[
  461. -1]):
  462. download_finished = cls.download_publish(log_type=log_type,
  463. crawler=crawler,
  464. strategy=strategy,
  465. video_dict=video_dict,
  466. rule_dict=rule_dict_1,
  467. our_uid=our_uid,
  468. oss_endpoint=oss_endpoint,
  469. env=env,
  470. machine=machine)
  471. # if download_finished is True:
  472. # download_cnt_1 += 1
  473. elif rule_2 is True:
  474. if download_cnt_2 < int(
  475. rule_dict_2['download_cnt'].replace("=", "")[-1].replace("<", "")[-1].replace(">",
  476. "")[
  477. -1]):
  478. download_finished = cls.download_publish(log_type=log_type,
  479. crawler=crawler,
  480. strategy=strategy,
  481. video_dict=video_dict,
  482. rule_dict=rule_dict_2,
  483. our_uid=our_uid,
  484. oss_endpoint=oss_endpoint,
  485. env=env,
  486. machine=machine)
  487. # if download_finished is True:
  488. # download_cnt_2 += 1
  489. else:
  490. Common.logger(log_type, crawler).info("不满足下载规则\n")
  491. # Common.logger(log_type, crawler).info(f"feeds: {feeds}\n")
  492. # if pcursor == "no_more":
  493. # Common.logger(log_type, crawler).info(f"作者,{out_uid},已经到底了,没有更多内容了\n")
  494. # return
  495. # cls.get_videoList(log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine,
  496. # pcursor=pcursor)
  497. # time.sleep(random.randint(1, 3))
  498. @classmethod
  499. def repeat_video(cls, log_type, crawler, video_id, video_title, publish_time, env, machine):
  500. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}" or (platform="{cls.platform}" and video_title="{video_title}" and publish_time="{publish_time}") """
  501. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  502. return len(repeat_video)
  503. @classmethod
  504. def download_publish(cls, log_type, crawler, strategy, video_dict, rule_dict, our_uid, oss_endpoint, env, machine):
  505. try:
  506. download_finished = False
  507. if cls.repeat_video(log_type, crawler, video_dict['video_id'], video_dict['video_title'],
  508. video_dict['publish_time_str'], env, machine) != 0:
  509. Common.logger(log_type, crawler).info('视频已下载\n')
  510. # elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, crawler, "3cd128") for x in y]:
  511. # Common.logger(log_type, crawler).info('视频已下载\n')
  512. elif any(word if word in video_dict['video_title'] else False for word in
  513. cls.filter_words(log_type, crawler)) is True:
  514. Common.logger(log_type, crawler).info('标题已中过滤词\n')
  515. else:
  516. # 下载视频
  517. Common.download_method(log_type=log_type, crawler=crawler, text='video',
  518. title=video_dict['video_title'], url=video_dict['video_url'])
  519. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  520. if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
  521. # 删除视频文件夹
  522. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  523. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  524. return
  525. # ffmpeg_dict = Common.ffmpeg(log_type, crawler,
  526. # f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  527. # if ffmpeg_dict is None or ffmpeg_dict['size'] == 0:
  528. # Common.logger(log_type, crawler).warning(f"下载的视频无效,已删除\n")
  529. # # 删除视频文件夹
  530. # shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  531. # return download_finished
  532. # 下载封面
  533. Common.download_method(log_type=log_type, crawler=crawler, text='cover',
  534. title=video_dict['video_title'], url=video_dict['cover_url'])
  535. # 保存视频信息至txt
  536. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  537. # 上传视频
  538. Common.logger(log_type, crawler).info("开始上传视频...")
  539. our_video_id = Publish.upload_and_publish(log_type=log_type,
  540. crawler=crawler,
  541. strategy=strategy,
  542. our_uid=our_uid,
  543. env=env,
  544. oss_endpoint=oss_endpoint)
  545. if env == 'dev':
  546. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  547. else:
  548. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  549. Common.logger(log_type, crawler).info("视频上传完成")
  550. if our_video_id is None:
  551. Common.logger(log_type, crawler).warning(f"our_video_id:{our_video_id} 删除该视频文件夹")
  552. # 删除视频文件夹
  553. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  554. return download_finished
  555. # 视频信息保存数据库
  556. insert_sql = f""" insert into crawler_video(video_id,
  557. user_id,
  558. out_user_id,
  559. platform,
  560. strategy,
  561. out_video_id,
  562. video_title,
  563. cover_url,
  564. video_url,
  565. duration,
  566. publish_time,
  567. play_cnt,
  568. crawler_rule,
  569. width,
  570. height)
  571. values({our_video_id},
  572. {our_uid},
  573. "{video_dict['user_id']}",
  574. "{cls.platform}",
  575. "定向爬虫策略",
  576. "{video_dict['video_id']}",
  577. "{video_dict['video_title']}",
  578. "{video_dict['cover_url']}",
  579. "{video_dict['video_url']}",
  580. {int(video_dict['duration'])},
  581. "{video_dict['publish_time_str']}",
  582. {int(video_dict['play_cnt'])},
  583. '{json.dumps(rule_dict)}',
  584. {int(video_dict['video_width'])},
  585. {int(video_dict['video_height'])}) """
  586. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  587. MysqlHelper.update_values(log_type, crawler, insert_sql, env, machine)
  588. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  589. # 视频写入飞书
  590. Feishu.insert_columns(log_type, 'kuaishou', "fYdA8F", "ROWS", 1, 2)
  591. upload_time = int(time.time())
  592. values = [[our_video_id,
  593. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  594. "定向榜",
  595. str(video_dict['video_id']),
  596. video_dict['video_title'],
  597. our_video_link,
  598. video_dict['play_cnt'],
  599. video_dict['comment_cnt'],
  600. video_dict['like_cnt'],
  601. video_dict['share_cnt'],
  602. video_dict['duration'],
  603. f"{video_dict['video_width']}*{video_dict['video_height']}",
  604. video_dict['publish_time_str'],
  605. video_dict['user_name'],
  606. video_dict['user_id'],
  607. video_dict['avatar_url'],
  608. video_dict['cover_url'],
  609. video_dict['video_url']]]
  610. time.sleep(1)
  611. Feishu.update_values(log_type, 'kuaishou', "fYdA8F", "E2:Z2", values)
  612. Common.logger(log_type, crawler).info(f"视频已保存至云文档\n")
  613. download_finished = True
  614. return download_finished
  615. except Exception as e:
  616. Common.logger(log_type, crawler).error(f"download_publish:{e}\n")
  617. @classmethod
  618. def get_follow_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine):
  619. # user_list = cls.get_user_list(log_type=log_type, crawler=crawler, sheetid="bTSzxW", env=env, machine=machine)
  620. user_list = get_user_from_mysql(log_type, crawler, crawler, env)
  621. for user in user_list:
  622. spider_link = user["spider_link"]
  623. out_uid = spider_link.split('/')[-1]
  624. user_name = user["nick_name"]
  625. our_uid = user["media_id"]
  626. Common.logger(log_type, crawler).info(f"开始抓取 {user_name} 用户主页视频\n")
  627. cls.get_videoList(log_type=log_type,
  628. crawler=crawler,
  629. strategy=strategy,
  630. our_uid=our_uid,
  631. out_uid=out_uid,
  632. oss_endpoint=oss_endpoint,
  633. env=env,
  634. machine=machine)
  635. if __name__ == "__main__":
  636. KuaiShouFollow.get_videoList(log_type="follow",
  637. crawler="kuaishou",
  638. strategy="定向爬虫策略",
  639. our_uid="54719554",
  640. out_uid="3xnk3wbm3vfiha6",
  641. oss_endpoint="out",
  642. env="dev",
  643. machine="local")
  644. # print(KuaiShouFollow.get_out_user_info("follow", "kuaishou", "3xnk3wbm3vfiha6"))
  645. # print(Follow.get_out_user_info("follow", "kuaishou", "3x5wgjhfc7tx8ue"))