xiaoniangao_author_scheduling.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/3/13
  4. import json
  5. import os
  6. import random
  7. import shutil
  8. import sys
  9. import time
  10. import requests
  11. import urllib3
  12. sys.path.append(os.getcwd())
  13. from common.common import Common
  14. from common.scheduling_db import MysqlHelper
  15. from common.publish import Publish
  16. from common.feishu import Feishu
  17. from common.public import get_config_from_mysql
  18. proxies = {"http": None, "https": None}
  19. class XiaoniangaoAuthorScheduling:
  20. platform = "小年糕"
  21. # 小程序个人主页视频列表翻页参数
  22. next_t = None
  23. # 基础门槛规则
  24. @staticmethod
  25. def download_rule(log_type, crawler, video_dict, rule_dict):
  26. """
  27. 下载视频的基本规则
  28. :param log_type: 日志
  29. :param crawler: 哪款爬虫
  30. :param video_dict: 视频信息,字典格式
  31. :param rule_dict: 规则信息,字典格式
  32. :return: 满足规则,返回 True;反之,返回 False
  33. """
  34. rule_playCnt_min = rule_dict.get('playCnt', {}).get('min', 0)
  35. rule_playCnt_max = rule_dict.get('playCnt', {}).get('max', 100000000)
  36. if rule_playCnt_max == 0:
  37. rule_playCnt_max = 100000000
  38. rule_duration_min = rule_dict.get('duration', {}).get('min', 0)
  39. rule_duration_max = rule_dict.get('duration', {}).get('max', 100000000)
  40. if rule_duration_max == 0:
  41. rule_duration_max = 100000000
  42. rule_period_min = rule_dict.get('period', {}).get('min', 0)
  43. # rule_period_max = rule_dict.get('period', {}).get('max', 100000000)
  44. # if rule_period_max == 0:
  45. # rule_period_max = 100000000
  46. #
  47. # rule_fans_min = rule_dict.get('fans', {}).get('min', 0)
  48. # rule_fans_max = rule_dict.get('fans', {}).get('max', 100000000)
  49. # if rule_fans_max == 0:
  50. # rule_fans_max = 100000000
  51. #
  52. # rule_videos_min = rule_dict.get('videos', {}).get('min', 0)
  53. # rule_videos_max = rule_dict.get('videos', {}).get('max', 100000000)
  54. # if rule_videos_max == 0:
  55. # rule_videos_max = 100000000
  56. rule_like_min = rule_dict.get('like', {}).get('min', 0)
  57. rule_like_max = rule_dict.get('like', {}).get('max', 100000000)
  58. if rule_like_max == 0:
  59. rule_like_max = 100000000
  60. rule_videoWidth_min = rule_dict.get('videoWidth', {}).get('min', 0)
  61. rule_videoWidth_max = rule_dict.get('videoWidth', {}).get('max', 100000000)
  62. if rule_videoWidth_max == 0:
  63. rule_videoWidth_max = 100000000
  64. rule_videoHeight_min = rule_dict.get('videoHeight', {}).get('min', 0)
  65. rule_videoHeight_max = rule_dict.get('videoHeight', {}).get('max', 100000000)
  66. if rule_videoHeight_max == 0:
  67. rule_videoHeight_max = 100000000
  68. rule_shareCnt_min = rule_dict.get('shareCnt', {}).get('min', 0)
  69. rule_shareCnt_max = rule_dict.get('shareCnt', {}).get('max', 100000000)
  70. if rule_shareCnt_max == 0:
  71. rule_shareCnt_max = 100000000
  72. rule_commentCnt_min = rule_dict.get('commentCnt', {}).get('min', 0)
  73. rule_commentCnt_max = rule_dict.get('commentCnt', {}).get('max', 100000000)
  74. if rule_commentCnt_max == 0:
  75. rule_commentCnt_max = 100000000
  76. Common.logger(log_type, crawler).info(f'rule_duration_max:{rule_duration_max} >= duration:{int(float(video_dict["duration"]))} >= rule_duration_min:{int(rule_duration_min)}')
  77. Common.logger(log_type, crawler).info(f'rule_playCnt_max:{int(rule_playCnt_max)} >= play_cnt:{int(video_dict["play_cnt"])} >= rule_playCnt_min:{int(rule_playCnt_min)}')
  78. Common.logger(log_type, crawler).info(f'now:{int(time.time())} - publish_time_stamp:{int(video_dict["publish_time_stamp"])} <= {3600 * 24 * int(rule_period_min)}')
  79. Common.logger(log_type, crawler).info(f'rule_like_max:{int(rule_like_max)} >= like_cnt:{int(video_dict["like_cnt"])} >= rule_like_min:{int(rule_like_min)}')
  80. Common.logger(log_type, crawler).info(f'rule_commentCnt_max:{int(rule_commentCnt_max)} >= comment_cnt:{int(video_dict["comment_cnt"])} >= rule_commentCnt_min:{int(rule_commentCnt_min)}')
  81. Common.logger(log_type, crawler).info(f'rule_shareCnt_max:{int(rule_shareCnt_max)} >= share_cnt:{int(video_dict["share_cnt"])} >= rule_shareCnt_min:{int(rule_shareCnt_min)}')
  82. Common.logger(log_type, crawler).info(f'rule_videoWidth_max:{int(rule_videoWidth_max)} >= video_width:{int(video_dict["video_width"])} >= rule_videoWidth_min:{int(rule_videoWidth_min)}')
  83. Common.logger(log_type, crawler).info(f'rule_videoHeight_max:{int(rule_videoHeight_max)} >= video_height:{int(video_dict["video_height"])} >= rule_videoHeight_min:{int(rule_videoHeight_min)}')
  84. if int(rule_duration_max) >= int(float(video_dict["duration"])) >= int(rule_duration_min) \
  85. and int(rule_playCnt_max) >= int(video_dict['play_cnt']) >= int(rule_playCnt_min) \
  86. and int(time.time()) - int(video_dict["publish_time_stamp"]) <= 3600 * 24 * int(rule_period_min) \
  87. and int(rule_like_max) >= int(video_dict['like_cnt']) >= int(rule_like_min) \
  88. and int(rule_commentCnt_max) >= int(video_dict['comment_cnt']) >= int(rule_commentCnt_min) \
  89. and int(rule_shareCnt_max) >= int(video_dict['share_cnt']) >= int(rule_shareCnt_min) \
  90. and int(rule_videoWidth_max) >= int(video_dict['video_width']) >= int(rule_videoWidth_min) \
  91. and int(rule_videoHeight_max) >= int(video_dict['video_height']) >= int(rule_videoHeight_min):
  92. return True
  93. else:
  94. return False
  95. @classmethod
  96. def repeat_video(cls, log_type, crawler, video_id, env):
  97. sql = f""" select * from crawler_video where platform="小年糕" and out_video_id="{video_id}"; """
  98. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  99. return len(repeat_video)
  100. # 获取个人主页视频
  101. @classmethod
  102. def get_videoList(cls, log_type, crawler, strategy, p_mid, uid, rule_dict, oss_endpoint, env):
  103. while True:
  104. url = "https://api.xiaoniangao.cn/profile/list_album"
  105. headers = {
  106. "X-Mid": '1fb47aa7a860d9',
  107. "X-Token-Id": '9f2cb91f9952c107ecb73642083e1dec-1145266232',
  108. "content-type": "application/json",
  109. "uuid": 'f40c2e7c-3cfb-4804-b513-608c0280268c',
  110. "Accept-Encoding": "gzip,compress,br,deflate",
  111. "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X)"
  112. " AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 "
  113. "MicroMessenger/8.0.20(0x18001435) NetType/WIFI Language/zh_CN",
  114. "Referer": 'https://servicewechat.com/wxd7911e4c177690e4/654/page-frame.html'
  115. }
  116. json_text = {
  117. "visited_mid": str(p_mid),
  118. "start_t": cls.next_t,
  119. "qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!690x385r/crop/690x385/interlace/1/format/jpg",
  120. "h_qs": "imageMogr2/gravity/center/rotate/$/thumbnail/!120x120r/crop/120x120/interlace/1/format/jpg",
  121. "limit": 20,
  122. "token": '54e4c603f7bf3dc009c86b49ed91be36',
  123. "uid": 'f40c2e7c-3cfb-4804-b513-608c0280268c',
  124. "proj": "ma",
  125. "wx_ver": "8.0.23",
  126. "code_ver": "3.68.0",
  127. "log_common_params": {
  128. "e": [{
  129. "data": {
  130. "page": "profilePage",
  131. "topic": "public"
  132. }
  133. }],
  134. "ext": {
  135. "brand": "iPhone",
  136. "device": "iPhone 11",
  137. "os": "iOS 14.7.1",
  138. "weixinver": "8.0.23",
  139. "srcver": "2.24.7",
  140. "net": "wifi",
  141. "scene": "1089"
  142. },
  143. "pj": "1",
  144. "pf": "2",
  145. "session_id": "7468cf52-00ea-432e-8505-6ea3ad7ec164"
  146. }
  147. }
  148. urllib3.disable_warnings()
  149. r = requests.post(url=url, headers=headers, json=json_text, proxies=proxies, verify=False)
  150. if 'data' not in r.text or r.status_code != 200:
  151. Common.logger(log_type, crawler).info(f"get_videoList:{r.text}\n")
  152. cls.next_t = None
  153. return
  154. elif 'list' not in r.json()['data']:
  155. Common.logger(log_type, crawler).info(f"get_videoList:{r.json()}\n")
  156. cls.next_t = None
  157. return
  158. elif len(r.json()['data']['list']) == 0:
  159. Common.logger(log_type, crawler).info(f"没有更多数据啦~\n")
  160. cls.next_t = None
  161. return
  162. else:
  163. cls.next_t = r.json()["data"]["next_t"]
  164. feeds = r.json()["data"]["list"]
  165. for i in range(len(feeds)):
  166. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  167. xiaoniangao_title = feeds[i].get("title", "").strip().replace("\n", "") \
  168. .replace("/", "").replace("\r", "").replace("#", "") \
  169. .replace(".", "。").replace("\\", "").replace("&NBSP", "") \
  170. .replace(":", "").replace("*", "").replace("?", "") \
  171. .replace("?", "").replace('"', "").replace("<", "") \
  172. .replace(">", "").replace("|", "").replace(" ", "") \
  173. .replace('"', '').replace("'", '')
  174. # 随机取一个表情/符号
  175. emoji = random.choice(get_config_from_mysql(log_type, crawler, env, "emoji"))
  176. # 生成最终标题,标题list[表情+title, title+表情]随机取一个
  177. video_title = random.choice([f"{emoji}{xiaoniangao_title}", f"{xiaoniangao_title}{emoji}"])
  178. # 视频 ID
  179. video_id = feeds[i].get("vid", "")
  180. # 播放量
  181. play_cnt = feeds[i].get("play_pv", 0)
  182. # 点赞量
  183. like_cnt = feeds[i].get("favor", {}).get("total", 0)
  184. # 评论数
  185. comment_cnt = feeds[i].get("comment_count", 0)
  186. # 分享量
  187. share_cnt = feeds[i].get("share", 0)
  188. # 时长
  189. duration = int(feeds[i].get("du", 0) / 1000)
  190. # 宽和高
  191. video_width = int(feeds[i].get("w", 0))
  192. video_height = int(feeds[i].get("h", 0))
  193. # 发布时间
  194. publish_time_stamp = int(int(feeds[i].get("t", 0)) / 1000)
  195. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  196. # 用户名 / 头像
  197. user_name = feeds[i].get("album_user", {}).get("nick", "").strip().replace("\n", "") \
  198. .replace("/", "").replace("快手", "").replace(" ", "") \
  199. .replace(" ", "").replace("&NBSP", "").replace("\r", "")
  200. avatar_url = feeds[i].get("album_user", {}).get("hurl", "")
  201. # 用户 ID
  202. profile_id = feeds[i]["id"]
  203. # 用户 mid
  204. profile_mid = feeds[i]["mid"]
  205. # 视频封面
  206. cover_url = feeds[i].get("url", "")
  207. # 视频播放地址
  208. video_url = feeds[i].get("v_url", "")
  209. video_dict = {
  210. "video_id": video_id,
  211. "video_title": video_title,
  212. "duration": duration,
  213. "play_cnt": play_cnt,
  214. "like_cnt": like_cnt,
  215. "comment_cnt": comment_cnt,
  216. "share_cnt": share_cnt,
  217. "user_name": user_name,
  218. "publish_time_stamp": publish_time_stamp,
  219. "publish_time_str": publish_time_str,
  220. "video_width": video_width,
  221. "video_height": video_height,
  222. "avatar_url": avatar_url,
  223. "profile_id": profile_id,
  224. "profile_mid": profile_mid,
  225. "cover_url": cover_url,
  226. "video_url": video_url,
  227. "session": f"xiaoniangao-author-{int(time.time())}"
  228. }
  229. for k, v in video_dict.items():
  230. Common.logger(log_type, crawler).info(f"{k}:{v}")
  231. if int(time.time()) - publish_time_stamp > 3600 * 24 * int(rule_dict.get('period', {}).get('min', 0)):
  232. Common.logger(log_type, crawler).info(f"发布时间超过3天:{publish_time_str}\n")
  233. cls.next_t = None
  234. return
  235. # 过滤无效视频
  236. if video_title == "" or video_id == "" or video_url == "":
  237. Common.logger(log_type, crawler).info("无效视频\n")
  238. # 抓取基础规则过滤
  239. elif cls.download_rule(log_type, crawler, video_dict, rule_dict) is False:
  240. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  241. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env) != 0:
  242. Common.logger(log_type, crawler).info('视频已下载\n')
  243. # 过滤词
  244. elif any(str(word) if str(word) in video_title else False for word in get_config_from_mysql(log_type, crawler, env, "filter", action="")) is True:
  245. Common.logger(log_type, crawler).info("视频已中过滤词\n")
  246. else:
  247. cls.download_publish(log_type=log_type,
  248. crawler=crawler,
  249. strategy=strategy,
  250. video_dict=video_dict,
  251. rule_dict=rule_dict,
  252. uid=uid,
  253. oss_endpoint=oss_endpoint,
  254. env=env)
  255. # 下载/上传
  256. @classmethod
  257. def download_publish(cls, log_type, crawler, strategy, video_dict, rule_dict, uid, oss_endpoint, env):
  258. # 下载封面
  259. Common.download_method(log_type=log_type, crawler=crawler, text="cover", title=video_dict["video_title"], url=video_dict["cover_url"])
  260. # 下载视频
  261. Common.download_method(log_type=log_type, crawler=crawler, text="video", title=video_dict["video_title"], url=video_dict["video_url"])
  262. # 保存视频信息至 "./videos/{download_video_title}/info.txt"
  263. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  264. # 上传视频
  265. Common.logger(log_type, crawler).info("开始上传视频...")
  266. our_video_id = Publish.upload_and_publish(log_type=log_type,
  267. crawler=crawler,
  268. strategy=strategy,
  269. our_uid=uid,
  270. env=env,
  271. oss_endpoint=oss_endpoint)
  272. if env == "dev":
  273. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  274. else:
  275. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  276. Common.logger(log_type, crawler).info("视频上传完成")
  277. if our_video_id is None:
  278. # 删除视频文件夹
  279. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  280. return
  281. insert_sql = f""" insert into crawler_video(video_id,
  282. out_user_id,
  283. platform,
  284. strategy,
  285. out_video_id,
  286. video_title,
  287. cover_url,
  288. video_url,
  289. duration,
  290. publish_time,
  291. play_cnt,
  292. crawler_rule,
  293. width,
  294. height)
  295. values({our_video_id},
  296. "{video_dict['profile_id']}",
  297. "{cls.platform}",
  298. "定向爬虫策略",
  299. "{video_dict['video_id']}",
  300. "{video_dict['video_title']}",
  301. "{video_dict['cover_url']}",
  302. "{video_dict['video_url']}",
  303. {int(video_dict['duration'])},
  304. "{video_dict['publish_time_str']}",
  305. {int(video_dict['play_cnt'])},
  306. '{json.dumps(rule_dict)}',
  307. {int(video_dict['video_width'])},
  308. {int(video_dict['video_height'])}) """
  309. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  310. MysqlHelper.update_values(log_type, crawler, insert_sql, env)
  311. Common.logger(log_type, crawler).info('视频信息插入数据库成功!')
  312. # 视频写入飞书
  313. Feishu.insert_columns(log_type, crawler, "Wu0CeL", "ROWS", 1, 2)
  314. # 视频ID工作表,首行写入数据
  315. upload_time = int(time.time())
  316. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  317. "用户主页",
  318. str(video_dict['video_id']),
  319. str(video_dict['video_title']),
  320. our_video_link,
  321. video_dict['play_cnt'],
  322. video_dict['comment_cnt'],
  323. video_dict['like_cnt'],
  324. video_dict['share_cnt'],
  325. video_dict['duration'],
  326. f"{video_dict['video_width']}*{video_dict['video_height']}",
  327. str(video_dict['publish_time_str']),
  328. str(video_dict['user_name']),
  329. str(video_dict['profile_id']),
  330. str(video_dict['profile_mid']),
  331. str(video_dict['avatar_url']),
  332. str(video_dict['cover_url']),
  333. str(video_dict['video_url'])]]
  334. time.sleep(1)
  335. Feishu.update_values(log_type, crawler, "Wu0CeL", "F2:Z2", values)
  336. Common.logger(log_type, crawler).info('视频信息写入飞书成功\n')
  337. # 获取所有关注列表的用户视频
  338. @classmethod
  339. def get_follow_videos(cls, log_type, crawler, user_list, rule_dict, strategy, oss_endpoint, env):
  340. if len(user_list) == 0:
  341. Common.logger(log_type, crawler).warning(f"抓取用户列表为空\n")
  342. return
  343. for user in user_list:
  344. # Common.logger(log_type, crawler).info(f"user:{user}")
  345. try:
  346. user_name = user['nick_name']
  347. profile_mid = user['link']
  348. uid = user['uid']
  349. Common.logger(log_type, crawler).info(f"获取 {user_name} 主页视频")
  350. cls.get_videoList(log_type=log_type,
  351. crawler=crawler,
  352. strategy=strategy,
  353. p_mid=profile_mid,
  354. rule_dict=rule_dict,
  355. uid=uid,
  356. oss_endpoint=oss_endpoint,
  357. env=env)
  358. cls.next_t = None
  359. time.sleep(1)
  360. except Exception as e:
  361. Common.logger(log_type, crawler).error(f"get_follow_videos:{e}\n")
  362. if __name__ == "__main__":
  363. # print(XiaoniangaoAuthorScheduling.repeat_video("follow", "xiaoniangao", "4919087666", "prod", "aliyun"))
  364. # print(XiaoniangaoAuthorScheduling.repeat_video("follow", "xiaoniangao", "4919087666", "dev"))
  365. # XiaoniangaoAuthorScheduling.get_users()
  366. pass