kuaishou_author_scheduling_new.py 21 KB

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