kuaishou_follow.py 38 KB

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