kanyikan_recommend_plus.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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_2919617999651782659", "wxv_2850432480192151552", "wxv_3162169938824904711",
  39. "wxv_2941471556667604997", "wxv_2925481910364127233", "wxv_2704001417933733890"])
  40. # "wxv_3061881796591828994", "wxv_2893555716505255939", "wxv_2892156962760310787",
  41. # "wxv_2978003449110118403", "wxv_2896072238624571394", "wxv_2789689742178189313",
  42. # "wxv_2915541877196898305", "wxv_2922703348296826885", "wxv_2799987508020346881","wxv_2704001417933733890"])
  43. channelid = random.choice(
  44. ["200201", "200", "208", "208201"])
  45. switchnewuser = random.choice(
  46. ["0", "1"])
  47. switchprofile = random.choice(
  48. ["0", "1"])
  49. subscene = random.choice(
  50. ["1089", "1074", "208"])
  51. params = random.choice([{
  52. 'session': session,
  53. "offset": 0,
  54. "wxaVersion": "3.9.2",
  55. "count": "10",
  56. "channelid": channelid,
  57. "scene": '310',
  58. "subscene": subscene,
  59. "clientVersion": '8.0.18',
  60. "sharesearchid": '0',
  61. "nettype": 'wifi',
  62. "switchprofile": switchprofile,
  63. "switchnewuser": switchnewuser,
  64. }, {
  65. "session": session,
  66. "wxaVersion": "3.17.8",
  67. "channelid": channelid,
  68. "vid": vid,
  69. "offset": 0,
  70. "count": "15",
  71. "scene": '310',
  72. "subscene": subscene,
  73. "model": "MacBookPro14%2C111.6.7",
  74. "nettype": 'wifi',
  75. "clientVersion": '3.5.5',
  76. "sharesearchid": '0',
  77. "presearchid": "17530764723864413041",
  78. "sharesource": "0",
  79. "isFromUgc": "false",
  80. "ad": 0,
  81. "switchprofile": switchprofile,
  82. "switchnewuser": switchnewuser,
  83. }])
  84. header = {
  85. 'Host': 'search.weixin.qq.com',
  86. 'Content-Type': 'application/json',
  87. 'X-WX-ClientVersion': '0x33050520',
  88. 'X-WECHAT-UIN': 'b2hfbTQ1WGNjSzQxemdfanpMSml1TEtfbEtsVQ==',
  89. 'Accept': '*/*',
  90. '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',
  91. 'Referer': 'https://servicewechat.com/wxbb9a805eb4f9533c/268/page-frame.html',
  92. 'Accept-Language': 'zh-cn'
  93. }
  94. urllib3.disable_warnings()
  95. response = requests.get(url=url, headers=header, params=params, proxies=proxies, verify=False)
  96. # print(response)
  97. if "data" not in response.text:
  98. Common.logger(log_type, crawler).info("获取视频list时,session过期,随机睡眠 31-50 秒")
  99. Common.logging(log_type, crawler, env, "获取视频list时,session过期,随机睡眠 31-50 秒")
  100. # 如果返回空信息,则随机睡眠 31-40 秒
  101. time.sleep(random.randint(31, 40))
  102. cls.get_videoList(log_type, crawler, our_uid, rule_dict, env)
  103. elif "items" not in response.json()["data"]:
  104. Common.logger(log_type, crawler).info(f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
  105. Common.logging(log_type, crawler, env, f"get_feeds:{response.json()},随机睡眠 1-3 分钟")
  106. # 如果返回空信息,则随机睡眠 1-3 分钟
  107. time.sleep(random.randint(60, 180))
  108. cls.get_videoList(log_type, crawler, our_uid, rule_dict, env)
  109. feeds = response.json().get("data", {}).get("items", "")
  110. if feeds == "":
  111. Common.logger(log_type, crawler).info(f"feeds:{feeds}")
  112. Common.logging(log_type, crawler, env, f"feeds:{feeds}")
  113. return
  114. for i in range(len(feeds)):
  115. try:
  116. video_title = feeds[i].get("title", "").strip().replace("\n", "") \
  117. .replace("/", "").replace("\\", "").replace("\r", "") \
  118. .replace(":", "").replace("*", "").replace("?", "") \
  119. .replace("?", "").replace('"', "").replace("<", "") \
  120. .replace(">", "").replace("|", "").replace(" ", "") \
  121. .replace("&NBSP", "").replace(".", "。").replace(" ", "") \
  122. .replace("'", "").replace("#", "").replace("Merge", "")
  123. publish_time_stamp = feeds[i].get("date", 0)
  124. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  125. # 获取播放地址
  126. if "videoInfo" not in feeds[i]:
  127. video_url = ""
  128. elif "mpInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  129. if len(feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"]) > 2:
  130. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][2]["url"]
  131. else:
  132. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["mpInfo"]["urlInfo"][0]["url"]
  133. elif "ctnInfo" in feeds[i]["videoInfo"]["videoCdnInfo"]:
  134. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["ctnInfo"]["urlInfo"][0]["url"]
  135. else:
  136. video_url = feeds[i]["videoInfo"]["videoCdnInfo"]["urlInfo"][0]["url"]
  137. videoId = feeds[i].get("videoId", "")
  138. videoId = "{}kyk_plus".format(videoId)
  139. playCount = int(feeds[i].get("playCount", 0))
  140. shared_cnt = int(feeds[i].get("shared_cnt", 0))
  141. video_dict = {
  142. "video_title": video_title,
  143. "video_id": videoId,
  144. "play_cnt": feeds[i].get("playCount", 0),
  145. "like_cnt": feeds[i].get("liked_cnt", 0),
  146. "comment_cnt": feeds[i].get("comment_cnt", 0),
  147. "share_cnt": feeds[i].get("shared_cnt", 0),
  148. "duration": feeds[i].get("mediaDuration", 0),
  149. "video_width": feeds[i].get("short_video_info", {}).get("width", 0),
  150. "video_height": feeds[i].get("short_video_info", {}).get("height", 0),
  151. "publish_time_stamp": publish_time_stamp,
  152. "publish_time_str": publish_time_str,
  153. "user_name": feeds[i].get("source", "").strip().replace("\n", ""),
  154. "user_id": feeds[i].get("openid", ""),
  155. "avatar_url": feeds[i].get("bizIcon", ""),
  156. "cover_url": feeds[i].get("thumbUrl", ""),
  157. "video_url": video_url,
  158. "session": session,
  159. }
  160. for k, v in video_dict.items():
  161. Common.logger(log_type, crawler).info(f"{k}:{v}")
  162. Common.logging(log_type, crawler, env, f"video_dict:{video_dict}")
  163. video_percent = '%.2f' % (shared_cnt / playCount)
  164. if float(video_percent) <= 0.05:
  165. Common.logger(log_type, crawler).info(f"分享/播放<0.05:{video_percent}\n")
  166. Common.logging(log_type, crawler, env, f"分享/播放<0.05:{video_percent}\n")
  167. continue
  168. if video_dict["video_id"] == "" or video_dict["video_title"] == "" or video_dict["video_url"] == "":
  169. Common.logger(log_type, crawler).info("无效视频\n")
  170. Common.logging(log_type, crawler, env, "无效视频\n")
  171. elif download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  172. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  173. Common.logging(log_type, crawler, env, "不满足抓取规则\n")
  174. elif any(str(word) if str(word) in video_dict["video_title"] else False
  175. for word in get_config_from_mysql(log_type=log_type,
  176. source=crawler,
  177. env=env,
  178. text="filter",
  179. action="")) is True:
  180. Common.logger(log_type, crawler).info('已中过滤词\n')
  181. Common.logging(log_type, crawler, env, '已中过滤词\n')
  182. elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
  183. Common.logger(log_type, crawler).info('视频已下载\n')
  184. Common.logging(log_type, crawler, env, '视频已下载\n')
  185. else:
  186. video_dict["out_user_id"] = video_dict["user_id"]
  187. video_dict["platform"] = crawler
  188. video_dict["strategy"] = log_type
  189. video_dict["strategy_type"] = "data"
  190. video_dict["out_video_id"] = video_dict["video_id"]
  191. video_dict["width"] = video_dict["video_width"]
  192. video_dict["height"] = video_dict["video_height"]
  193. video_dict["crawler_rule"] = json.dumps(rule_dict)
  194. video_dict["user_id"] = our_uid
  195. video_dict["publish_time"] = video_dict["publish_time_str"]
  196. mq.send_msg(video_dict)
  197. time.sleep(random.randint(10, 15))
  198. except Exception as e:
  199. Common.logger(log_type, crawler).error(f"抓取单条视频异常:{e}\n")
  200. Common.logging(log_type, crawler, env, f"抓取单条视频异常:{e}\n")
  201. except Exception as e:
  202. Common.logger(log_type, crawler).error(f"抓取列表页时异常:{e}\n")
  203. Common.logging(log_type, crawler, env, f"抓取列表页时异常:{e}\n")
  204. if __name__ == "__main__":
  205. KanyikanRecommend.get_videoList(
  206. log_type="recommend",
  207. crawler="kanyikan",
  208. env="prod",
  209. rule_dict={'share_cnt': {'min': 300, 'max': 0}},
  210. our_uid=64080779
  211. )