kuaishou_author_scheduling_new.py 20 KB

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