kanyikan_recommend_plus.py 13 KB

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