xiaoniangao_author_v2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. import json
  2. import os
  3. import random
  4. import sys
  5. import time
  6. import uuid
  7. import requests
  8. from common.mq import MQ
  9. sys.path.append(os.getcwd())
  10. from common.common import Common
  11. from common import AliyunLogger, PiaoQuanPipeline
  12. from common.public import get_config_from_mysql, clean_title
  13. def tunnel_proxies():
  14. # 隧道域名:端口号
  15. tunnel = "q796.kdltps.com:15818"
  16. # 用户名密码方式
  17. username = "t17772369458618"
  18. password = "5zqcjkmy"
  19. tunnel_proxies = {
  20. "http": "http://%(user)s:%(pwd)s@%(proxy)s/"
  21. % {"user": username, "pwd": password, "proxy": tunnel},
  22. "https": "http://%(user)s:%(pwd)s@%(proxy)s/"
  23. % {"user": username, "pwd": password, "proxy": tunnel},
  24. }
  25. return tunnel_proxies
  26. class XiaoNianGaoAuthor:
  27. def __init__(self, platform, mode, rule_dict, env, user_list):
  28. self.platform = platform
  29. self.mode = mode
  30. self.rule_dict = rule_dict
  31. self.env = env
  32. self.user_list = user_list
  33. self.mq = MQ(topic_name="topic_crawler_etl_" + self.env)
  34. self.download_count = 0
  35. def get_author_list(self):
  36. # 每轮只抓取定量的数据,到达数量后自己退出
  37. max_count = int(self.rule_dict.get("videos_cnt", {}).get("min", 300))
  38. for user_dict in self.user_list:
  39. if self.download_count <= max_count:
  40. self.get_video_list(user_dict)
  41. time.sleep(random.randint(1, 15))
  42. else:
  43. AliyunLogger.logging(
  44. code="2000",
  45. platform=self.platform,
  46. mode=self.mode,
  47. env=self.env,
  48. message="本轮已经抓取足够数量的视频,已经自动退出",
  49. )
  50. Common.logging(
  51. log_type=self.mode,
  52. crawler=self.platform,
  53. env=self.env,
  54. message="本轮已经抓取足够数量的视频,已经自动退出",
  55. )
  56. return
  57. def get_video_list(self, user_dict):
  58. next_t = -1
  59. # 只抓取更新的视频,如果刷到已经更新的立即退出
  60. url = "https://kapi-xng-app.xiaoniangao.cn/v1/album/user_public"
  61. headers = {
  62. "Host": "kapi-xng-app.xiaoniangao.cn",
  63. "content-type": "application/json; charset=utf-8",
  64. "accept": "*/*",
  65. "verb": "POST",
  66. "accept-language": "zh-cn",
  67. "date": "Wed, 01 Nov 2023 11:53:22 GMT",
  68. "x-token-id": "",
  69. "x-signaturemethod": "hmac-sha1",
  70. }
  71. while True:
  72. payload = {
  73. "token": "",
  74. "limit": 20,
  75. "start_t": next_t,
  76. "visited_mid": int(user_dict["link"]),
  77. "share_width": 300,
  78. "share_height": 240,
  79. }
  80. response = requests.request(
  81. "POST",
  82. url,
  83. headers=headers,
  84. data=json.dumps(payload),
  85. proxies=tunnel_proxies(),
  86. )
  87. if "data" not in response.text or response.status_code != 200:
  88. Common.logger(self.mode, self.platform).info(
  89. f"get_videoList:{response.text}\n"
  90. )
  91. Common.logging(
  92. log_type=self.mode,
  93. crawler=self.platform,
  94. env=self.env,
  95. message=f"get_videoList:{response.text}\n"
  96. )
  97. AliyunLogger.logging(
  98. code="2000",
  99. platform=self.platform,
  100. mode=self.mode,
  101. env=self.env,
  102. message=f"get_videoList:{response.text}\n",
  103. )
  104. return
  105. elif "list" not in response.json()["data"]:
  106. Common.logger(self.mode, self.platform).info(
  107. f"get_videoList:{response.json()}\n"
  108. )
  109. Common.logging(
  110. log_type=self.mode,
  111. crawler=self.platform,
  112. env=self.env,
  113. message=f"get_videoList:{response.json()}\n"
  114. )
  115. AliyunLogger.logging(
  116. code="2000",
  117. platform=self.platform,
  118. mode=self.mode,
  119. env=self.env,
  120. message=f"get_videoList:{response.text}\n",
  121. )
  122. return
  123. elif len(response.json()["data"]["list"]) == 0:
  124. Common.logger(self.mode, self.platform).info(f"没有更多数据啦~\n")
  125. Common.logging(
  126. log_type=self.mode,
  127. crawler=self.platform,
  128. env=self.env,
  129. message=f"没有更多数据啦~\n"
  130. )
  131. AliyunLogger.logging(
  132. code="2000",
  133. platform=self.platform,
  134. mode=self.mode,
  135. env=self.env,
  136. message=f"没有更多数据啦~\n",
  137. )
  138. return
  139. else:
  140. next_t = response.json()["data"]["next_t"]
  141. feeds = response.json()["data"]["list"]
  142. for video_obj in feeds:
  143. try:
  144. AliyunLogger.logging(
  145. code="1001",
  146. platform=self.platform,
  147. mode=self.mode,
  148. env=self.env,
  149. message="扫描到一条视频",
  150. )
  151. Common.logging(
  152. log_type=self.mode,
  153. crawler=self.platform,
  154. env=self.env,
  155. message=f"扫描到一条视频"
  156. )
  157. self.process_video_obj(video_obj, user_dict)
  158. except Exception as e:
  159. AliyunLogger.logging(
  160. code="3000",
  161. platform=self.platform,
  162. mode=self.mode,
  163. env=self.env,
  164. data=video_obj,
  165. message="抓取单条视频异常, 报错原因是: {}".format(e),
  166. )
  167. Common.logging(
  168. log_type=self.mode,
  169. crawler=self.platform,
  170. env=self.env,
  171. message="抓取单条视频异常, 报错原因是: {}".format(e),
  172. )
  173. def process_video_obj(self, video_obj, user_dict):
  174. trace_id = self.platform + str(uuid.uuid1())
  175. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  176. xiaoniangao_title = clean_title(video_obj.get("title", ""))
  177. # 随机取一个表情/符号
  178. emoji = random.choice(
  179. get_config_from_mysql(self.mode, self.platform, self.env, "emoji")
  180. )
  181. # 生成最终标题,标题list[表情+title, title+表情]随机取一个
  182. video_title = random.choice(
  183. [f"{emoji}{xiaoniangao_title}", f"{xiaoniangao_title}{emoji}"]
  184. )
  185. # 发布时间
  186. publish_time_stamp = int(int(video_obj.get("t", 0)) / 1000)
  187. publish_time_str = time.strftime(
  188. "%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp)
  189. )
  190. # 用户名 / 头像
  191. user_name = (
  192. video_obj.get("user", {})
  193. .get("nick", "")
  194. .strip()
  195. .replace("\n", "")
  196. .replace("/", "")
  197. .replace(" ", "")
  198. .replace(" ", "")
  199. .replace("&NBSP", "")
  200. .replace("\r", "")
  201. )
  202. video_dict = {
  203. "video_title": video_title,
  204. "video_id": video_obj.get("vid", ""),
  205. "duration": int(video_obj.get("du", 0) / 1000),
  206. "play_cnt": video_obj.get("play_pv", 0),
  207. "like_cnt": video_obj.get("favor", {}).get("total", 0),
  208. "comment_cnt": video_obj.get("comment_count", 0),
  209. "share_cnt": video_obj.get("share", 0),
  210. "user_name": user_name,
  211. "publish_time_stamp": publish_time_stamp,
  212. "publish_time_str": publish_time_str,
  213. "update_time_stamp": int(time.time()),
  214. "video_width": int(video_obj.get("w", 0)),
  215. "video_height": int(video_obj.get("h", 0)),
  216. "avatar_url": video_obj.get("user", {}).get("hurl", ""),
  217. "profile_id": video_obj["id"],
  218. "profile_mid": video_obj.get("user", {}).get("mid", ""),
  219. "cover_url": video_obj.get("url", ""),
  220. "video_url": video_obj.get("v_url", ""),
  221. "session": f"xiaoniangao-author-{int(time.time())}",
  222. "out_user_id": video_obj["id"],
  223. "platform": self.platform,
  224. "strategy": self.mode,
  225. "out_video_id": video_obj.get("vid", ""),
  226. }
  227. for k, v in video_dict.items():
  228. Common.logger(self.mode, self.platform).info(f"{k}:{v}")
  229. pipeline = PiaoQuanPipeline(
  230. platform=self.platform,
  231. mode=self.mode,
  232. rule_dict=self.rule_dict,
  233. env=self.env,
  234. item=video_dict,
  235. trace_id=trace_id,
  236. )
  237. flag = pipeline.process_item()
  238. if flag:
  239. video_dict["width"] = video_dict["video_width"]
  240. video_dict["height"] = video_dict["video_height"]
  241. video_dict["crawler_rule"] = json.dumps(self.rule_dict)
  242. video_dict["user_id"] = user_dict["uid"]
  243. video_dict["publish_time"] = video_dict["publish_time_str"]
  244. # print(video_dict)
  245. self.mq.send_msg(video_dict)
  246. self.download_count += 1
  247. AliyunLogger.logging(
  248. code="1002",
  249. platform=self.platform,
  250. mode=self.mode,
  251. env=self.env,
  252. data=video_dict,
  253. trace_id=trace_id,
  254. message="成功发送 MQ 至 ETL",
  255. )
  256. Common.logging(
  257. log_type=self.mode,
  258. crawler=self.platform,
  259. env=self.env,
  260. message="成功发送 MQ 至 ETL",
  261. )
  262. # if __name__ == "__main__":
  263. # XNGA = XiaoNianGaoAuthor(
  264. # platform="xiaoniangao",
  265. # mode="author",
  266. # rule_dict={},
  267. # env="prod",
  268. # user_list=[{"link": 295640510, "uid": "12334"}],
  269. # )
  270. # XNGA.get_author_list()