haitunzhufu_recommend3.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. # -*- coding: utf-8 -*-
  2. # @Author: luojunhui
  3. # @Time: 2023/10/18
  4. import json
  5. import os
  6. import random
  7. import sys
  8. import time
  9. from datetime import datetime
  10. import requests
  11. from base64 import b64encode, b64decode
  12. from Crypto.Cipher import AES
  13. from Crypto.Util.Padding import pad, unpad
  14. from common.mq import MQ
  15. sys.path.append(os.getcwd())
  16. from common.common import Common
  17. from common.scheduling_db import MysqlHelper
  18. from common.public import get_config_from_mysql, download_rule_v2, clean_title
  19. class AESCipher:
  20. def __init__(self, key):
  21. self.key = key.encode('utf-8') # 需要一个bytes类型的key
  22. self.iv = self.key # 在这个例子中,key和iv是相同的
  23. def encrypt(self, data):
  24. cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
  25. ct_bytes = cipher.encrypt(pad(data.encode('utf-8'), AES.block_size))
  26. ct = b64encode(ct_bytes).decode('utf-8')
  27. return ct
  28. def decrypt(self, data):
  29. try:
  30. ct = b64decode(data.encode('utf-8'))
  31. cipher = AES.new(self.key, AES.MODE_CBC, self.iv)
  32. pt = unpad(cipher.decrypt(ct), AES.block_size)
  33. return pt.decode('utf-8')
  34. except Exception as e:
  35. print("Incorrect decryption")
  36. return None
  37. class HTZFScheduling:
  38. def __init__(self, log_type, crawler, rule_dict, env, our_uid):
  39. self.platform = "haitunzhufu"
  40. self.log_type = log_type
  41. self.crawler = crawler
  42. self.rule_dict = rule_dict
  43. self.env = env
  44. self.our_uid = our_uid
  45. self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
  46. self.download_count = 0
  47. def repeat_video(self, video_id):
  48. sql = f""" select * from crawler_video where platform in ("{self.crawler}","{self.platform}") and out_video_id="{video_id}"; """
  49. repeat_video = MysqlHelper.get_values(
  50. self.log_type, self.crawler, sql, self.env
  51. )
  52. return len(repeat_video)
  53. # 获取视频id_list
  54. def get_videoList(self, page_id):
  55. time.sleep(random.randint(5, 10))
  56. url = 'https://haitun.wyapi.cn/videos/api.videos/getItem'
  57. headers = {
  58. 'xweb_xhr': '1',
  59. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 MicroMessenger/6.8.0(0x16080000) NetType/WIFI MiniProgramEnv/Mac MacWechat/WMPF XWEB/30817',
  60. 'content-type': 'application/json',
  61. 'accept': '*/*',
  62. 'sec-fetch-site': 'cross-site',
  63. 'sec-fetch-mode': 'cors',
  64. 'sec-fetch-dest': 'empty',
  65. 'referer': 'https://servicewechat.com/wxcc35cbbc445d331a/2/page-frame.html',
  66. 'accept-encoding': 'gzip, deflate, br',
  67. 'accept-language': 'en'
  68. }
  69. params = {
  70. 'mark': '',
  71. 'page': page_id
  72. }
  73. response = requests.get(url, headers=headers, params=params)
  74. ori_result = response.json()
  75. key = "xlc2ze7qnqg8xi1d"
  76. cipher = AESCipher(key)
  77. decrypted_text = cipher.decrypt(ori_result['data'])
  78. result = json.loads(decrypted_text)
  79. if "list" not in result or response.status_code != 200:
  80. Common.logger(self.log_type, self.crawler).info(
  81. f"get_videoList:{response.text}\n"
  82. )
  83. Common.logging(
  84. self.log_type,
  85. self.crawler,
  86. self.env,
  87. f"get_videoList:{response.text}\n",
  88. )
  89. return
  90. elif len(result["list"]) == 0:
  91. Common.logger(self.log_type, self.crawler).info(f"没有更多数据啦~\n")
  92. Common.logging(self.log_type, self.crawler, self.env, f"没有更多数据啦~\n")
  93. return
  94. else:
  95. data_list = result["list"]
  96. for video_obj in data_list:
  97. try:
  98. self.process_video_obj(video_obj)
  99. except Exception as e:
  100. Common.logger(self.log_type, self.crawler).error(f"抓取单条视频异常:{e}\n")
  101. Common.logging(
  102. self.log_type, self.crawler, self.env, f"抓取单条视频异常:{e}\n"
  103. )
  104. def process_video_obj(self, video_obj):
  105. video_id = video_obj.get("id", 0)
  106. video_title = clean_title(video_obj.get("name", "no title"))
  107. video_time = 0
  108. publish_time_str = video_obj.get("create_at", "")
  109. # 将时间字符串转换为 datetime 对象
  110. dt = datetime.strptime(publish_time_str, '%Y-%m-%d %H:%M:%S')
  111. # 将 datetime 对象转换为时间戳
  112. publish_time_stamp = int(datetime.timestamp(dt))
  113. user_name = ""
  114. video_dict = {
  115. "video_title": video_title,
  116. "video_id": video_id,
  117. "duration": video_time,
  118. "play_cnt": int(video_obj.get("num_read", 0)),
  119. "like_cnt": int(video_obj.get("num_like", 0)),
  120. "comment_cnt": int(video_obj.get("num_comment", 0)),
  121. "share_cnt": 0,
  122. "user_name": user_name,
  123. "publish_time_stamp": publish_time_stamp,
  124. "publish_time_str": publish_time_str,
  125. "video_width": 0,
  126. "video_height": 0,
  127. "profile_id": 0,
  128. "profile_mid": 0,
  129. "session": f"haitunzhufu-{int(time.time())}",
  130. }
  131. for k, v in video_dict.items():
  132. Common.logger(self.log_type, self.crawler).info(f"{k}:{v}")
  133. Common.logging(
  134. self.log_type, self.crawler, self.env, f"{video_dict}"
  135. )
  136. # 过滤无效视频
  137. if video_title == "" or video_dict["video_id"] == "":
  138. Common.logger(self.log_type, self.crawler).info("无效视频\n")
  139. Common.logging(self.log_type, self.crawler, self.env, "无效视频\n")
  140. # 抓取基础规则过滤
  141. elif (
  142. download_rule_v2(
  143. log_type=self.log_type,
  144. crawler=self.crawler,
  145. video_dict=video_dict,
  146. rule_dict=self.rule_dict,
  147. )
  148. is False
  149. ):
  150. Common.logger(self.log_type, self.crawler).info("不满足抓取规则\n")
  151. Common.logging(
  152. self.log_type, self.crawler, self.env, "不满足抓取规则\n"
  153. )
  154. elif (
  155. any(
  156. str(word)
  157. if str(word) in video_dict["video_title"]
  158. else False
  159. for word in get_config_from_mysql(
  160. log_type=self.log_type,
  161. source=self.crawler,
  162. env=self.env,
  163. text="filter",
  164. action="",
  165. )
  166. )
  167. is True
  168. ):
  169. Common.logger(self.log_type, self.crawler).info("已中过滤词\n")
  170. Common.logging(self.log_type, self.crawler, self.env, "已中过滤词\n")
  171. elif self.repeat_video(video_dict["video_id"]) != 0:
  172. Common.logger(self.log_type, self.crawler).info("视频已下载\n")
  173. Common.logging(self.log_type, self.crawler, self.env, "视频已下载\n")
  174. else:
  175. video_dict["out_user_id"] = video_obj.get("profile_id", 0)
  176. video_dict["platform"] = self.crawler
  177. video_dict["strategy"] = self.log_type
  178. video_dict["out_video_id"] = str(video_dict["video_id"])
  179. video_dict["width"] = video_dict["video_width"]
  180. video_dict["height"] = video_dict["video_height"]
  181. video_dict["crawler_rule"] = json.dumps(self.rule_dict)
  182. video_dict["user_id"] = self.our_uid
  183. video_dict["publish_time"] = video_dict["publish_time_str"]
  184. video_dict["video_url"] = video_obj['cover']
  185. video_dict["avatar_url"] = ""
  186. video_dict["cover_url"] = video_obj['cover'] + "&vframe/png/offset/1/w/200"
  187. # print(json.dumps(video_dict, ensure_ascii=False, indent=4))
  188. self.download_count += 1
  189. self.mq.send_msg(video_dict)
  190. if __name__ == "__main__":
  191. ZL = HTZFScheduling(
  192. log_type="recommend",
  193. crawler="htzf",
  194. rule_dict={},
  195. our_uid="luojunhuihaoshuai",
  196. env="dev"
  197. )
  198. for i in range(4):
  199. ZL.get_videoList(page_id=i + 1)
  200. print(ZL.download_count)