kanyikan_recommend_plus.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding: utf-8 -*-
  2. # @Time: 2023/10/26
  3. import json
  4. import os
  5. import random
  6. import sys
  7. import time
  8. import requests
  9. import urllib3
  10. sys.path.append(os.getcwd())
  11. from common.mq import MQ
  12. from common.common import Common
  13. from common.scheduling_db import MysqlHelper
  14. from common.public import get_config_from_mysql, download_rule
  15. proxies = {"http": None, "https": None}
  16. class KanyikanRecommend:
  17. platform = "看一看"
  18. strategy = "随机数据抓取"
  19. @classmethod
  20. def repeat_video(cls, log_type, crawler, video_id, env):
  21. sql = f""" select * from crawler_video where platform in ("{crawler}","{cls.platform}") and create_time>='2023-10-09' and out_video_id="{video_id}"; """
  22. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env)
  23. return len(repeat_video)
  24. @classmethod
  25. def get_videoList(cls, log_type, crawler, our_uid, rule_dict, env):
  26. mq = MQ(topic_name="topic_crawler_etl_" + env)
  27. try:
  28. Common.logger(log_type, crawler).info(f"正在抓取列表页{crawler}")
  29. Common.logging(log_type, crawler, env, f"正在抓取列表页")
  30. Common.logger(log_type, crawler).info(f"Test{crawler}")
  31. session = Common.get_session(log_type, crawler, env)
  32. if session is None:
  33. time.sleep(1)
  34. cls.get_videoList(log_type, crawler, our_uid, rule_dict, env)
  35. for i in range(20):
  36. url = 'https://search.weixin.qq.com/cgi-bin/recwxa/recwxavideolist?'
  37. vid = random.choice(
  38. ["wxv_3085195467366072322", "wxv_3168759197371744256", "wxv_2531110975320653824",
  39. "wxv_3169383102658494466", "wxv_3169411010382987271", "wxv_3164795491776495618",
  40. "wxv_3137409288953544707", "wxv_3153044290563145729", "wxv_3073760962312290305",
  41. "wxv_3132868021706571779", "wxv_2957593102221950978", "wxv_2953293015190863873",
  42. "wxv_3170817826585378816", "wxv_3140044619146313734", "wxv_3160584846952562692",
  43. "wxv_2567806762238574592", "wxv_2916859703706779654", "wxv_3141488224696090625",
  44. "wxv_2927799826199609344", "wxv_2990845422900461569", "wxv_3102057581600129026",])
  45. channelid = random.choice(
  46. ["200201", "200", "208", "208201"])
  47. switchnewuser = random.choice(
  48. ["0", "1"])
  49. switchprofile = random.choice(
  50. ["0", "1"])
  51. subscene = random.choice(
  52. ["1089", "1074", "208"])
  53. params = random.choice([{
  54. 'session': session,
  55. "offset": 0,
  56. "wxaVersion": "3.9.2",
  57. "count": "10",
  58. "channelid": channelid,
  59. "scene": '310',
  60. "subscene": subscene,
  61. "clientVersion": '8.0.18',
  62. "sharesearchid": '0',
  63. "nettype": 'wifi',
  64. "switchprofile": switchprofile,
  65. "switchnewuser": switchnewuser,
  66. }, {
  67. "session": session,
  68. "wxaVersion": "3.17.8",
  69. "channelid": channelid,
  70. "vid": vid,
  71. "offset": 0,
  72. "count": "15",
  73. "scene": '310',
  74. "subscene": subscene,
  75. "model": "MacBookPro14%2C111.6.7",
  76. "nettype": 'wifi',
  77. "clientVersion": '3.5.5',
  78. "sharesearchid": '0',
  79. "presearchid": "17530764723864413041",
  80. "sharesource": "0",
  81. "isFromUgc": "false",
  82. "ad": 0,
  83. "switchprofile": switchprofile,
  84. "switchnewuser": switchnewuser,
  85. }])
  86. header = {
  87. 'Host': 'search.weixin.qq.com',
  88. 'Content-Type': 'application/json',
  89. 'X-WX-ClientVersion': '0x33050520',
  90. 'X-WECHAT-UIN': 'b2hfbTQ1WGNjSzQxemdfanpMSml1TEtfbEtsVQ==',
  91. 'Accept': '*/*',
  92. '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',
  93. 'Referer': 'https://servicewechat.com/wxbb9a805eb4f9533c/268/page-frame.html',
  94. 'Accept-Language': 'zh-cn'
  95. }
  96. urllib3.disable_warnings()
  97. response = requests.get(url=url, headers=header, params=params, proxies=proxies, verify=False)
  98. # print(response)
  99. if "data" not in response.text:
  100. Common.logger(log_type, crawler).info("获取视频list时,session过期,随机睡眠 31-50 秒")
  101. Common.logging(log_type, crawler, env, "获取视频list时,session过期,随机睡眠 31-50 秒")
  102. # 如果返回空信息,则随机睡眠 31-40 秒
  103. time.sleep(random.randint(31, 40))
  104. cls.get_videoList(log_type, crawler, our_uid, rule_dict, env)
  105. elif "items" not in response.json()["data"]:
  106. Common.logger(log_type, crawler).info(f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
  107. Common.logging(log_type, crawler, env, f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
  108. # 如果返回空信息,则随机睡眠 1-3 分钟
  109. time.sleep(random.randint(60, 180))
  110. cls.get_videoList(log_type, crawler, our_uid, rule_dict, env)
  111. feeds = response.json().get("data", {}).get("items", "")
  112. if feeds == "":
  113. Common.logger(log_type, crawler).info(f"feeds:{feeds}")
  114. Common.logging(log_type, crawler, env, f"feeds:{feeds}")
  115. return
  116. for i in range(len(feeds)):
  117. try:
  118. video_title = feeds[i].get("title", "").strip().replace("\n", "") \
  119. .replace("/", "").replace("\\", "").replace("\r", "") \
  120. .replace(":", "").replace("*", "").replace("?", "") \
  121. .replace("?", "").replace('"', "").replace("<", "") \
  122. .replace(">", "").replace("|", "").replace(" ", "") \
  123. .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
  124. .replace("'", "").replace("#", "").replace("Merge", "")
  125. publish_time_stamp = feeds[i].get("date", 0)
  126. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  127. # 获取播放地址
  128. if "videoInfo" not in feeds[i]:
  129. video_url = ""
  130. elif "mpInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  131. if len(feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"]) > 2:
  132. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][2]["url"]
  133. else:
  134. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][0]["url"]
  135. elif "ctnInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  136. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["ctnInfo"]["urlInfo"][0]["url"]
  137. else:
  138. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["urlInfo"][0]["url"]
  139. videoId = feeds[i].get("videoId", "")
  140. videoId = "{}kyk_plus".format(videoId)
  141. playCount = int(feeds[i].get("playCount", 0))
  142. shared_cnt = int(feeds[i].get("shared_cnt", 0))
  143. video_dict = {
  144. "video_title": video_title,
  145. "video_id": videoId,
  146. "play_cnt": feeds[i].get("playCount", 0),
  147. "like_cnt": feeds[i].get("liked_cnt", 0),
  148. "comment_cnt": feeds[i].get("comment_cnt", 0),
  149. "share_cnt": feeds[i].get("shared_cnt", 0),
  150. "duration": feeds[i].get("mediaDuration", 0),
  151. "video_width": feeds[i].get("short_video_info", {}).get("width", 0),
  152. "video_height": feeds[i].get("short_video_info", {}).get("height", 0),
  153. "publish_time_stamp": publish_time_stamp,
  154. "publish_time_str": publish_time_str,
  155. "user_name": feeds[i].get("source", "").strip().replace("\n", ""),
  156. "user_id": feeds[i].get("openid", ""),
  157. "avatar_url": feeds[i].get("bizIcon", ""),
  158. "cover_url": feeds[i].get("thumbUrl", ""),
  159. "video_url": video_url,
  160. "session": session,
  161. }
  162. for k, v in video_dict.items():
  163. Common.logger(log_type, crawler).info(f"{k}:{v}")
  164. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  165. video_percent = '%.2f' % (shared_cnt / playCount)
  166. if float(video_percent) < 0.05:
  167. Common.logger(log_type, crawler).info(f"分享/播放:{video_percent}\n")
  168. Common.logging(log_type, crawler, env, f"分享/播放:{video_percent}\n")
  169. continue
  170. elif shared_cnt < 800:
  171. Common.logger(log_type, crawler).info(f"播放量:{playCount}\n")
  172. Common.logging(log_type, crawler, env, f"播放量:{playCount}\n")
  173. continue
  174. if video_dict["video_id"] == "" or video_dict["video_title"] == "" or video_dict["video_url"] == "":
  175. Common.logger(log_type, crawler).info("无效视频\n")
  176. Common.logging(log_type, crawler, env, "无效视频\n")
  177. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  178. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  179. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  180. elif any(str(word) if str(word) in video_dict["video_title"] else False
  181. for word in get_config_from_mysql(log_type=log_type,
  182. source=crawler,
  183. env=env,
  184. text="filter",
  185. action="")) is True:
  186. Common.logger(log_type, crawler).info('已中过滤词\n')
  187. Common.logging(log_type, crawler, env, '已中过滤词\n')
  188. elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
  189. Common.logger(log_type, crawler).info('视频已下载\n')
  190. Common.logging(log_type, crawler, env, '视频已下载\n')
  191. else:
  192. video_dict["out_user_id"] = video_dict["user_id"]
  193. video_dict["platform"] = crawler
  194. video_dict["strategy"] = log_type
  195. video_dict["strategy_type"] = "data"
  196. video_dict["out_video_id"] = video_dict["video_id"]
  197. video_dict["width"] = video_dict["video_width"]
  198. video_dict["height"] = video_dict["video_height"]
  199. video_dict["crawler_rule"] = json.dumps(rule_dict)
  200. video_dict["user_id"] = our_uid
  201. video_dict["publish_time"] = video_dict["publish_time_str"]
  202. mq.send_msg(video_dict)
  203. time.sleep(random.randint(10, 15))
  204. except Exception as e:
  205. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  206. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  207. except Exception as e:
  208. Common.logger(log_type, crawler).error(f"抓取列表页时异常:{e}\n")
  209. Common.logging(log_type, crawler, env, f"抓取列表页时异常:{e}\n")
  210. if __name__ == "__main__":
  211. KanyikanRecommend.get_videoList(
  212. log_type="recommend",
  213. crawler="kanyikan",
  214. env="prod",
  215. rule_dict={'share_cnt': {'min': 300, 'max': 0}},
  216. our_uid=64080779
  217. )