kuaishou_author_scheduling_new.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. # -*- coding: utf-8 -*-
  2. # @Time: 2023/11/07
  3. import datetime
  4. import os
  5. import random
  6. import sys
  7. import time
  8. from datetime import date, timedelta
  9. import cv2
  10. import requests
  11. import json
  12. import urllib3
  13. from common.feishu import Feishu
  14. sys.path.append(os.getcwd())
  15. from common.common import Common
  16. from common import AliyunLogger
  17. from common.mq import MQ
  18. from requests.adapters import HTTPAdapter
  19. from common.scheduling_db import MysqlHelper
  20. from common.public import random_title, get_config_from_mysql, download_rule
  21. from common.limit import AuthorLimit
  22. class KuaishouauthorScheduling:
  23. platform = "快手"
  24. download_cnt = 0
  25. limiter = AuthorLimit(platform="kuaishou", mode="author")
  26. @classmethod
  27. def videos_cnt(cls, rule_dict):
  28. videos_cnt = rule_dict.get("videos_cnt", {}).get("min", 0)
  29. if videos_cnt == 0:
  30. videos_cnt = 1000
  31. return videos_cnt
  32. @classmethod
  33. def video_title(cls, log_type, crawler, env, title):
  34. title_split1 = title.split(" #")
  35. if title_split1[0] != "":
  36. title1 = title_split1[0]
  37. else:
  38. title1 = title_split1[-1]
  39. title_split2 = title1.split(" #")
  40. if title_split2[0] != "":
  41. title2 = title_split2[0]
  42. else:
  43. title2 = title_split2[-1]
  44. title_split3 = title2.split("@")
  45. if title_split3[0] != "":
  46. title3 = title_split3[0]
  47. else:
  48. title3 = title_split3[-1]
  49. video_title = title3.strip().replace("\n", "") \
  50. .replace("/", "").replace("快手", "").replace(" ", "") \
  51. .replace(" ", "").replace("&NBSP", "").replace("\r", "") \
  52. .replace("#", "").replace(".", "。").replace("\\", "") \
  53. .replace(":", "").replace("*", "").replace("?", "") \
  54. .replace("?", "").replace('"', "").replace("<", "") \
  55. .replace(">", "").replace("|", "").replace("@", "").replace('"', '').replace("'", '')[:40]
  56. if video_title.replace(" ", "") == "" or video_title == "。。。" or video_title == "...":
  57. return random_title(log_type, crawler, env, text='title')
  58. else:
  59. return video_title
  60. @classmethod
  61. def get_cookie(cls, log_type, crawler, env):
  62. select_sql = f""" select * from crawler_config where source="{crawler}" """
  63. configs = MysqlHelper.get_values(log_type, crawler, select_sql, env, action="")
  64. for config in configs:
  65. if "cookie" in config["config"]:
  66. cookie_dict = {
  67. "cookie_id": config["id"],
  68. "title": config["title"].strip(),
  69. "cookie": dict(eval(config["config"]))["cookie"].strip(),
  70. "update_time": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(config["update_time"] / 1000))),
  71. "operator": config["operator"].strip()
  72. }
  73. return cookie_dict
  74. @classmethod
  75. def get_videoList(cls, log_type, crawler, user_dict, rule_dict, env):
  76. pcursor = ""
  77. mq = MQ(topic_name="topic_crawler_etl_" + env)
  78. count = 0
  79. special = 0
  80. for i in range(3):
  81. # while True:
  82. if count > 5:
  83. return
  84. time.sleep(random.randint(10, 50))
  85. url = "https://www.kuaishou.com/graphql"
  86. if user_dict['link'][0] == "V":
  87. link = user_dict["link"][3:]
  88. flag = user_dict["link"].split("_")[0]
  89. if flag == "V1":
  90. rule_dict = {
  91. 'period': {"min": 15, "max": 0},
  92. }
  93. special = 0.01
  94. elif flag == "V2":
  95. rule_dict = {
  96. 'period': {"min": 15, "max": 0},
  97. }
  98. special = 0.01
  99. elif flag == "V3":
  100. rule_dict = {
  101. 'period': {"min": 15, "max": 0},
  102. }
  103. special = 0.01
  104. else:
  105. link = user_dict["link"]
  106. payload = json.dumps({
  107. "operationName": "visionProfilePhotoList",
  108. "variables": {
  109. "userId": str(link.replace("https://www.kuaishou.com/profile/", "")),
  110. "pcursor": pcursor,
  111. "page": "profile"
  112. },
  113. "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"
  114. })
  115. cookie_list = cls.get_cookie(log_type, crawler, env)["cookie"]
  116. if ',' in cookie_list:
  117. cookies = cookie_list.split(',')
  118. else:
  119. cookies = [cookie_list]
  120. cookie = random.choice(cookies)
  121. headers = {
  122. 'Accept': '*/*',
  123. 'Content-Type': 'application/json',
  124. 'Origin': 'https://www.kuaishou.com',
  125. 'Cookie': cookie,
  126. # 'Cookie': "kpf=PC_WEB; clientid=3; did=web_b7830efe78a1e48daacb126b6f52ad05; userId=1299331643; didv=1711610963000; kuaishou.server.web_st=ChZrdWFpc2hvdS5zZXJ2ZXIud2ViLnN0EqABsqe9eHH9ZkvQs7beNfwe3IobrRFI_3HvvYRx7BGcVwVImonsmZgPXWpHF89uY-Fomry6l9EtimGUwt4EEF0xMeyMauj7ZvMndNTvjG8qro9yB-xtc6_iN0a6-peDQz6zxeUs6gQLkm58NFtCTDGsqWqMDs1ruDWlJiy-1GVqT59GI_AoJgukwXtTEaYFKzDSmUWv7qsJ0Ya1gDlsyPFO0hoSoJCKbxHIWXjzVWap_gGna5KjIiCdD9i3Uy2z2XGYS--wpIFP_h8k_AasD37nnju7rv_ocSgFMAE; kuaishou.server.web_ph=76097deb523bd30b37fa3d9f67200e5e4e72; kpn=KUAISHOU_VISION",
  127. 'Content-Length': '1260',
  128. 'Accept-Language': 'zh-CN,zh-Hans;q=0.9',
  129. 'Host': 'www.kuaishou.com',
  130. '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',
  131. 'Referer': f'https://www.kuaishou.com/profile/{link.replace("https://www.kuaishou.com/profile/", "")}',
  132. 'Accept-Encoding': 'gzip, deflate, br',
  133. 'Connection': 'keep-alive'
  134. }
  135. urllib3.disable_warnings()
  136. s = requests.session()
  137. # max_retries=3 重试3次
  138. s.mount('http://', HTTPAdapter(max_retries=3))
  139. s.mount('https://', HTTPAdapter(max_retries=3))
  140. response = s.post(url=url, headers=headers, data=payload, verify=False, timeout=10)
  141. response.close()
  142. # Common.logger(log_type, crawler).info(f"response:{response.text}\n")
  143. if response.status_code != 200:
  144. Common.logger(log_type, crawler).warning(f"response:{response.text}\n")
  145. AliyunLogger.logging(
  146. code="2000",
  147. platform=crawler,
  148. mode=log_type,
  149. env=env,
  150. message=f"response:{response.json()}\n"
  151. )
  152. return
  153. elif "data" not in response.json():
  154. Common.logger(log_type, crawler).warning(f"response:{response.json()}\n")
  155. AliyunLogger.logging(
  156. code="2000",
  157. platform=crawler,
  158. mode=log_type,
  159. env=env,
  160. message=f"response:{response.json()}\n"
  161. )
  162. Feishu.bot(log_type, 'kuaishou', f'快手cookie失效,请及时更换~')
  163. return
  164. elif "visionProfilePhotoList" not in response.json()["data"]:
  165. Common.logger(log_type, crawler).warning(f"response:{response.json()}\n")
  166. AliyunLogger.logging(
  167. code="2000",
  168. platform=crawler,
  169. mode=log_type,
  170. env=env,
  171. message=f"response:{response.json()}\n"
  172. )
  173. Feishu.bot(log_type, 'kuaishou', f'快手cookie失效,请及时更换~')
  174. return
  175. elif "feeds" not in response.json()["data"]["visionProfilePhotoList"]:
  176. Common.logger(log_type, crawler).warning(f"response:{response.json()}\n")
  177. AliyunLogger.logging(
  178. code="2000",
  179. platform=crawler,
  180. mode=log_type,
  181. env=env,
  182. message=f"response:{response.json()}\n"
  183. )
  184. return
  185. elif len(response.json()["data"]["visionProfilePhotoList"]["feeds"]) == 0:
  186. Common.logger(log_type, crawler).warning(f"没有更多视频啦 ~\n")
  187. AliyunLogger.logging(
  188. code="2001",
  189. platform=crawler,
  190. mode=log_type,
  191. env=env,
  192. message= f"没有更多视频啦 ~\n"
  193. )
  194. return
  195. pcursor = response.json()['data']['visionProfilePhotoList']['pcursor']
  196. feeds = response.json()['data']['visionProfilePhotoList']['feeds']
  197. for i in range(len(feeds)):
  198. try:
  199. Common.logger(log_type, crawler).info('扫描到一条视频\n')
  200. AliyunLogger.logging(
  201. code="1001",
  202. platform=crawler,
  203. mode=log_type,
  204. env=env,
  205. message='扫描到一条视频\n'
  206. )
  207. if cls.download_cnt >= cls.videos_cnt(rule_dict):
  208. Common.logger(log_type, crawler).info(f"已下载视频数:{cls.download_cnt}\n")
  209. AliyunLogger.logging(
  210. code="2002",
  211. platform=crawler,
  212. mode=log_type,
  213. env=env,
  214. message=f"已下载视频数:{cls.download_cnt}\n"
  215. )
  216. return
  217. user_name = feeds[i].get("author").get("name")
  218. video_title = feeds[i].get("photo", {}).get("caption", random_title(log_type, crawler, env, text='title'))
  219. video_title = cls.video_title(log_type, crawler, env, video_title)
  220. try:
  221. video_id = feeds[i].get("photo", {}).get("videoResource").get("h264", {}).get("videoId", "")
  222. video_width = feeds[i].get("photo", {}).get("videoResource").get("h264", {}).get("adaptationSet", {})[0].get("representation", {})[0].get("width", 0)
  223. video_height = feeds[i].get("photo", {}).get("videoResource").get("h264", {}).get("adaptationSet", {})[0].get("representation", {})[0].get("height", 0)
  224. except KeyError:
  225. video_id = feeds[i].get("photo", {}).get("videoResource").get("hevc", {}).get("videoId", "")
  226. video_width = feeds[i].get("photo", {}).get("videoResource").get("hevc", {}).get("adaptationSet", {})[0].get("representation", {})[0].get("width", 0)
  227. video_height = feeds[i].get("photo", {}).get("videoResource").get("hevc", {}).get("adaptationSet", {})[0].get("representation", {})[0].get("height", 0)
  228. publish_time_stamp = int(int(feeds[i].get('photo', {}).get('timestamp', 0)) / 1000)
  229. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  230. profile_userTop_photo = feeds[i].get('photo', {}).get('profileUserTopPhoto', '')
  231. viewCount = int(feeds[i].get('photo', {}).get('viewCount', 0))
  232. realLikeCount = int(feeds[i].get('photo', {}).get('realLikeCount', 0))
  233. if realLikeCount < 10000:
  234. AliyunLogger.logging(
  235. code="2004",
  236. platform=crawler,
  237. mode=log_type,
  238. env=env,
  239. message=f'点赞小于10000\n'
  240. )
  241. continue
  242. duration = cls.video_duration(feeds[i].get('photo', {}).get('photoUrl', ""))
  243. if int(duration) < 45:
  244. AliyunLogger.logging(
  245. code="2004",
  246. platform=crawler,
  247. mode=log_type,
  248. env=env,
  249. message=f'视频时常小于45秒\n'
  250. )
  251. continue
  252. # video_percent = '%.2f' % (realLikeCount / viewCount)
  253. # if special != 0:
  254. # special = float(special)
  255. # if float(video_percent) < special:
  256. # Common.logger(log_type, crawler).info(f"不符合条件:点赞/播放-{video_percent}\n")
  257. # AliyunLogger.logging(
  258. # code="2004",
  259. # platform=crawler,
  260. # mode=log_type,
  261. # env=env,
  262. # message=f"点赞量:{realLikeCount}\n"
  263. # )
  264. # continue
  265. video_dict = {'video_title': video_title,
  266. 'video_id': video_id,
  267. 'play_cnt': int(feeds[i].get('photo', {}).get('viewCount', 0)),
  268. 'like_cnt': int(feeds[i].get('photo', {}).get('realLikeCount', 0)),
  269. 'comment_cnt': 0,
  270. 'share_cnt': 0,
  271. 'video_width': video_width,
  272. 'video_height': video_height,
  273. 'duration': int(int(feeds[i].get('photo', {}).get('duration', 0)) / 1000),
  274. 'publish_time_stamp': publish_time_stamp,
  275. 'publish_time_str': publish_time_str,
  276. 'user_name': feeds[i].get('author', {}).get('name', ""),
  277. 'user_id': feeds[i].get('author', {}).get('id', ""),
  278. 'avatar_url': feeds[i].get('author', {}).get('headerUrl', ""),
  279. 'cover_url': feeds[i].get('photo', {}).get('coverUrl', ""),
  280. 'video_url': feeds[i].get('photo', {}).get('photoUrl', ""),
  281. 'session': f"kuaishou-{int(time.time())}"}
  282. for k, v in video_dict.items():
  283. Common.logger(log_type, crawler).info(f"{k}:{v}")
  284. AliyunLogger.logging(
  285. code="1000",
  286. platform=crawler,
  287. mode=log_type,
  288. env=env,
  289. message=f"{video_dict}\n"
  290. )
  291. if profile_userTop_photo != True:
  292. if int((int(time.time()) - int(publish_time_stamp)) / (3600*24)) > int(rule_dict.get("period", {}).get("max", 1000)):
  293. Common.logger(log_type, crawler).info(f'发布时间超过{int(rule_dict.get("period", {}).get("max", 1000))}天\n')
  294. AliyunLogger.logging(
  295. code="2004",
  296. platform=crawler,
  297. mode=log_type,
  298. env=env,
  299. message=f'发布时间超过{int(rule_dict.get("period", {}).get("max", 1000))}天\n'
  300. )
  301. return
  302. if video_dict["video_id"] == '' or video_dict["cover_url"] == '' or video_dict["video_url"] == '':
  303. Common.logger(log_type, crawler).info('无效视频\n')
  304. AliyunLogger.logging(
  305. code="2004",
  306. platform=crawler,
  307. mode=log_type,
  308. env=env,
  309. message='无效视频\n'
  310. )
  311. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  312. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  313. AliyunLogger.logging(
  314. code="2004",
  315. platform=crawler,
  316. mode=log_type,
  317. env=env,
  318. message='不满足抓取规则\n'
  319. )
  320. elif any(str(word) if str(word) in video_dict["video_title"] else False
  321. for word in get_config_from_mysql(log_type=log_type,
  322. source=crawler,
  323. env=env,
  324. text="filter",
  325. action="")) is True:
  326. Common.logger(log_type, crawler).info('已中过滤词\n')
  327. AliyunLogger.logging(
  328. code="2004",
  329. platform=crawler,
  330. mode=log_type,
  331. env=env,
  332. message='已中过滤词\n'
  333. )
  334. elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
  335. count += 1
  336. Common.logger(log_type, crawler).info('视频已下载\n')
  337. AliyunLogger.logging(
  338. code="2002",
  339. platform=crawler,
  340. mode=log_type,
  341. env=env,
  342. message='视频已下载\n'
  343. )
  344. else:
  345. video_dict["out_user_id"] = video_dict["user_id"]
  346. video_dict["platform"] = crawler
  347. video_dict["strategy"] = log_type
  348. video_dict["out_video_id"] = video_dict["video_id"]
  349. video_dict["width"] = video_dict["video_width"]
  350. video_dict["height"] = video_dict["video_height"]
  351. video_dict["crawler_rule"] = json.dumps(rule_dict)
  352. video_dict["user_id"] = user_dict["uid"]
  353. video_dict["publish_time"] = video_dict["publish_time_str"]
  354. video_dict["strategy_type"] = log_type
  355. mq.send_msg(video_dict)
  356. current_time = datetime.datetime.now()
  357. timestamp = current_time.strftime("%Y-%m-%d %H:%M:%S")
  358. values = [[
  359. user_name,
  360. video_id,
  361. video_title,
  362. publish_time_str,
  363. timestamp,
  364. viewCount,
  365. realLikeCount,
  366. feeds[i].get('photo', {}).get('coverUrl', ""),
  367. feeds[i].get('photo', {}).get('photoUrl', "")
  368. ]]
  369. Feishu.insert_columns('kuaishou', 'kuaishou', "ue0rAF", "ROWS", 1, 2)
  370. time.sleep(0.5)
  371. Feishu.update_values('kuaishou', 'kuaishou', "ue0rAF", "A2:Z2", values)
  372. cls.download_cnt += 1
  373. AliyunLogger.logging(code="1002", message="成功发送至 ETL", data=video_dict)
  374. except Exception as e:
  375. Common.logger(log_type, crawler).warning(f"抓取单条视频异常:{e}\n")
  376. AliyunLogger.logging(
  377. code="3000",
  378. platform=crawler,
  379. mode=log_type,
  380. env=env,
  381. message=f"抓取单条视频异常:{e}\n"
  382. )
  383. @classmethod
  384. def repeat_video(cls, log_type, crawler, video_id, env):
  385. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and out_video_id="{video_id}"; """
  386. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  387. return len(repeat_video)
  388. @classmethod
  389. def get_author_videos(cls, log_type, crawler, user_list, rule_dict, env):
  390. for user_dict in user_list:
  391. try:
  392. Common.logger(log_type, crawler).info(f"开始抓取 {user_dict['nick_name']} 主页视频")
  393. AliyunLogger.logging(
  394. code="2000",
  395. platform=crawler,
  396. mode=log_type,
  397. env=env,
  398. message=f"开始抓取 {user_dict['nick_name']} 主页视频"
  399. )
  400. cls.download_cnt = 0
  401. cls.get_videoList(log_type=log_type,
  402. crawler=crawler,
  403. user_dict=user_dict,
  404. rule_dict=rule_dict,
  405. env=env)
  406. except Exception as e:
  407. Common.logger(log_type, crawler).warning(f"抓取用户{user_dict['nick_name']}主页视频时异常:{e}\n")
  408. AliyunLogger.logging(
  409. code="3000",
  410. platform=crawler,
  411. mode=log_type,
  412. env=env,
  413. message=f"抓取用户{user_dict['nick_name']}主页视频时异常:{e}\n"
  414. )
  415. @classmethod
  416. def video_duration(cls, filename):
  417. cap = cv2.VideoCapture(filename)
  418. if cap.isOpened():
  419. rate = cap.get(5)
  420. frame_num = cap.get(7)
  421. duration = frame_num / rate
  422. return duration
  423. return 0
  424. if __name__ == "__main__":
  425. print(KuaishouauthorScheduling.get_cookie("author", "kuaishou", "prod")["cookie"])
  426. pass