fqw_recommend.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import json
  2. import random
  3. import re
  4. import time
  5. import requests
  6. from common.common import Common
  7. from common.scheduling_db import MysqlHelper
  8. from common.mq import MQ
  9. from common.public import download_rule, get_config_from_mysql
  10. proxies = {"http": None, "https": None}
  11. class FqwRecommend:
  12. platform = ("福气旺")
  13. download_cnt = 0
  14. element_list = []
  15. i = 0
  16. @classmethod
  17. def repeat_video(cls, log_type, crawler, video_id, env):
  18. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and create_time>='2023-06-26' and out_video_id="{video_id}"; """
  19. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  20. return len(repeat_video)
  21. @classmethod
  22. def get_videoList(cls, log_type, crawler, our_uid, rule_dict, env):
  23. mq = MQ(topic_name="topic_crawler_etl_" + env)
  24. # uuid1 = str(uuid.uuid1())
  25. page = 1
  26. while True:
  27. try:
  28. Common.logger(log_type, crawler).info(f"正在抓取第{page}页")
  29. Common.logging(log_type, crawler, env, f"正在抓取第{page}页")
  30. url = "https://api.xinghetime.com/luckvideo/video/getRecommendVideos"
  31. payload = json.dumps({
  32. "baseParam": {
  33. "mid": "openid_o5Xjp4q2yKGEhqFEeYvwjPNZJzWY",
  34. "pageSource": "video-home"
  35. },
  36. "bizParam": {
  37. "pageSize": 3
  38. }
  39. })
  40. headers = {
  41. 'Host': 'api.xinghetime.com',
  42. 'accept': '*/*',
  43. 'content-type': 'application/json',
  44. 'accept-language': 'zh-cn',
  45. 'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E217 MicroMessenger/6.8.0(0x16080000) NetType/WIFI Language/en Branch/Br_trunk MiniProgramEnv/Mac',
  46. 'referer': 'https://servicewechat.com/wx8d8992849398a1cb/10/page-frame.html'
  47. }
  48. r = requests.post(url=url, headers=headers, data=payload, proxies=proxies, verify=False)
  49. if "data" not in r.text or r.status_code != 200:
  50. Common.logger(log_type, crawler).warning(f"get_videoList:{r.text}\n")
  51. Common.logging(log_type, crawler, env, f"get_videoList:{r.text}\n")
  52. return
  53. elif "data" not in r.json():
  54. Common.logger(log_type, crawler).info(f"get_videoList:{r.json()}\n")
  55. Common.logging(log_type, crawler, env, f"get_videoList:{r.json()}\n")
  56. return
  57. elif len(r.json()["data"]) == 0:
  58. Common.logger(log_type, crawler).warning(f"get_videoList:{r.json()['data']['list']}\n")
  59. Common.logging(log_type, crawler, env, f"get_videoList:{r.json()['data']['list']}\n")
  60. return
  61. else:
  62. # 视频列表
  63. feeds = r.json()["data"]
  64. for i in range(len(feeds)):
  65. try:
  66. if cls.download_cnt >= int(rule_dict.get("videos_cnt", {}).get("min", 10)):
  67. cls.i = 0
  68. cls.download_cnt = 0
  69. cls.element_list = []
  70. return
  71. cls.i += 1
  72. video_title = feeds[i].get("title", "").strip().replace("\n", "") \
  73. .replace("/", "").replace("\\", "").replace("\r", "") \
  74. .replace(":", "").replace("*", "").replace("?", "") \
  75. .replace("?", "").replace('"', "").replace("<", "") \
  76. .replace(">", "").replace("|", "").replace(" ", "") \
  77. .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
  78. .replace("'", "").replace("#", "").replace("Merge", "")
  79. publish_time_stamp = int(time.time())
  80. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  81. # 播放次数 提取数字
  82. play_count = feeds[i]["playCountFormat"]
  83. number = re.findall(r'\d+', play_count)
  84. if number:
  85. result = number[0]
  86. else:
  87. result = 0
  88. time_str = feeds[i]["durationFormat"]
  89. minutes, seconds = map(int, time_str.split(':'))
  90. # 计算总秒数
  91. total_seconds = minutes * 60 + seconds
  92. video_dict = {
  93. "video_title": video_title,
  94. "video_id": str(feeds[i]["videoId"]), # 视频id
  95. "publish_time_stamp": publish_time_stamp,
  96. "publish_time_str": publish_time_str,
  97. "category_id": int(feeds[i].get("category_id", 0)), # 视频来源(精彩推荐)
  98. "cover_url": feeds[i].get("coverImagePath", ""), # 视频封面
  99. "video_url": feeds[i]["videoPath"], # 视频链接
  100. # "duration_format": feeds[i]["durationFormat"], # 时长
  101. "click": int(feeds[i].get("click", 0)), # 点击数
  102. "video_width": int(feeds[i].get("width", 0)),
  103. "video_height": int(feeds[i].get("height", 0)),
  104. "user_name": feeds[i].get("source", "").strip().replace("\n", ""),
  105. "user_id": feeds[i].get("openid", ""),
  106. "play_cnt": int(result),
  107. "like_cnt": 0,
  108. "comment_cnt": 0,
  109. "share_cnt": 0,
  110. "duration": total_seconds,
  111. "session": ""
  112. }
  113. for k, v in video_dict.items():
  114. Common.logger(log_type, crawler).info(f"{k}:{v}")
  115. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  116. if video_dict["video_id"] == "" or video_dict["video_title"] == "" or video_dict[
  117. "video_url"] == "":
  118. Common.logger(log_type, crawler).info("无效视频\n")
  119. Common.logging(log_type, crawler, env, "无效视频\n")
  120. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict,
  121. rule_dict=rule_dict) is False:
  122. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  123. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  124. elif any(str(word) if str(word) in video_dict["video_title"] else False
  125. for word in get_config_from_mysql(log_type=log_type,
  126. source=crawler,
  127. env=env,
  128. text="filter",
  129. action="")) is True:
  130. Common.logger(log_type, crawler).info('已中过滤词\n')
  131. Common.logging(log_type, crawler, env, '已中过滤词\n')
  132. elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
  133. Common.logger(log_type, crawler).info('视频已下载\n')
  134. Common.logging(log_type, crawler, env, '视频已下载\n')
  135. else:
  136. video_dict["out_user_id"] = video_dict["user_id"]
  137. video_dict["platform"] = crawler
  138. video_dict["strategy"] = log_type
  139. video_dict["out_video_id"] = video_dict["video_id"]
  140. video_dict["width"] = video_dict["video_width"]
  141. video_dict["height"] = video_dict["video_height"]
  142. video_dict["crawler_rule"] = json.dumps(rule_dict)
  143. video_dict["user_id"] = our_uid
  144. video_dict["publish_time"] = video_dict["publish_time_str"]
  145. mq.send_msg(video_dict)
  146. cls.download_cnt += 1
  147. interval = random.randrange(5, 11)
  148. time.sleep(interval)
  149. except Exception as e:
  150. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  151. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  152. page += 1
  153. except Exception as e:
  154. Common.logger(log_type, crawler).error(f"抓取第{page}页时异常:{e}\n")
  155. Common.logging(log_type, crawler, env, f"抓取第{page}页时异常:{e}\n")
  156. if __name__ == "__main__":
  157. rule_dict1 = {"period": {"min": 365, "max": 365},
  158. "duration": {"min": 30, "max": 1800},
  159. "favorite_cnt": {"min": 0, "max": 0},
  160. "videos_cnt": {"min": 10, "max": 20},
  161. "share_cnt": {"min": 0, "max": 0}}
  162. FqwRecommend.get_videoList("recommend", "wangqifu,", "16QspO", rule_dict1, 'dev')