kuaishou_author_scheduling_new.py 22 KB

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