xiaoniangao_author_v2.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. 'authorization': 'hSNQ2s9pvPxvFn4LaQJxKQ6/7Is=',
  66. 'verb': 'POST',
  67. 'content-md5': 'c7b7f8663984e8800e3bcd9b44465083',
  68. 'x-b3-traceid': '2f9da41f960ae077',
  69. 'accept-language': 'zh-cn',
  70. 'date': 'Mon, 19 Jun 2023 06:41:17 GMT',
  71. 'x-token-id': '',
  72. 'x-signaturemethod': 'hmac-sha1',
  73. 'user-agent': 'xngapp/157 CFNetwork/1335.0.3.1 Darwin/21.6.0'
  74. }
  75. while True:
  76. payload = {
  77. "token": "",
  78. "limit": 20,
  79. "start_t": next_t,
  80. "visited_mid": int(user_dict["link"]),
  81. "share_width": 300,
  82. "share_height": 240,
  83. }
  84. response = requests.request(
  85. "POST",
  86. url,
  87. headers=headers,
  88. data=json.dumps(payload),
  89. proxies=tunnel_proxies(),
  90. )
  91. if "data" not in response.text or response.status_code != 200:
  92. Common.logger(self.mode, self.platform).info(
  93. f"get_videoList:{response.text}\n"
  94. )
  95. Common.logging(
  96. log_type=self.mode,
  97. crawler=self.platform,
  98. env=self.env,
  99. message=f"get_videoList:{response.text}\n"
  100. )
  101. AliyunLogger.logging(
  102. code="2000",
  103. platform=self.platform,
  104. mode=self.mode,
  105. env=self.env,
  106. message=f"get_videoList:{response.text}\n",
  107. )
  108. return
  109. elif "list" not in response.json()["data"]:
  110. Common.logger(self.mode, self.platform).info(
  111. f"get_videoList:{response.json()}\n"
  112. )
  113. Common.logging(
  114. log_type=self.mode,
  115. crawler=self.platform,
  116. env=self.env,
  117. message=f"get_videoList:{response.json()}\n"
  118. )
  119. AliyunLogger.logging(
  120. code="2000",
  121. platform=self.platform,
  122. mode=self.mode,
  123. env=self.env,
  124. message=f"get_videoList:{response.text}\n",
  125. )
  126. return
  127. elif len(response.json()["data"]["list"]) == 0:
  128. Common.logger(self.mode, self.platform).info(f"没有更多数据啦~\n")
  129. Common.logging(
  130. log_type=self.mode,
  131. crawler=self.platform,
  132. env=self.env,
  133. message=f"没有更多数据啦~\n"
  134. )
  135. AliyunLogger.logging(
  136. code="2000",
  137. platform=self.platform,
  138. mode=self.mode,
  139. env=self.env,
  140. message=f"没有更多数据啦~\n",
  141. )
  142. return
  143. else:
  144. next_t = response.json()["data"]["next_t"]
  145. feeds = response.json()["data"]["list"]
  146. for video_obj in feeds:
  147. try:
  148. AliyunLogger.logging(
  149. code="1001",
  150. platform=self.platform,
  151. mode=self.mode,
  152. env=self.env,
  153. message="扫描到一条视频",
  154. )
  155. Common.logging(
  156. log_type=self.mode,
  157. crawler=self.platform,
  158. env=self.env,
  159. message=f"扫描到一条视频"
  160. )
  161. self.process_video_obj(video_obj, user_dict)
  162. except Exception as e:
  163. AliyunLogger.logging(
  164. code="3000",
  165. platform=self.platform,
  166. mode=self.mode,
  167. env=self.env,
  168. data=video_obj,
  169. message="抓取单条视频异常, 报错原因是: {}".format(e),
  170. )
  171. Common.logging(
  172. log_type=self.mode,
  173. crawler=self.platform,
  174. env=self.env,
  175. message="抓取单条视频异常, 报错原因是: {}".format(e),
  176. )
  177. def process_video_obj(self, video_obj, user_dict):
  178. trace_id = self.platform + str(uuid.uuid1())
  179. # 标题,表情随机加在片头、片尾,或替代句子中间的标点符号
  180. xiaoniangao_title = clean_title(video_obj.get("title", ""))
  181. # 随机取一个表情/符号
  182. emoji = random.choice(
  183. get_config_from_mysql(self.mode, self.platform, self.env, "emoji")
  184. )
  185. # 生成最终标题,标题list[表情+title, title+表情]随机取一个
  186. video_title = random.choice(
  187. [f"{emoji}{xiaoniangao_title}", f"{xiaoniangao_title}{emoji}"]
  188. )
  189. # 发布时间
  190. publish_time_stamp = int(int(video_obj.get("t", 0)) / 1000)
  191. publish_time_str = time.strftime(
  192. "%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp)
  193. )
  194. # 用户名 / 头像
  195. user_name = (
  196. video_obj.get("user", {})
  197. .get("nick", "")
  198. .strip()
  199. .replace("\n", "")
  200. .replace("/", "")
  201. .replace(" ", "")
  202. .replace(" ", "")
  203. .replace("&NBSP", "")
  204. .replace("\r", "")
  205. )
  206. video_dict = {
  207. "video_title": video_title,
  208. "video_id": video_obj.get("vid", ""),
  209. "duration": int(video_obj.get("du", 0) / 1000),
  210. "play_cnt": video_obj.get("play_pv", 0),
  211. "like_cnt": video_obj.get("favor", {}).get("total", 0),
  212. "comment_cnt": video_obj.get("comment_count", 0),
  213. "share_cnt": video_obj.get("share", 0),
  214. "user_name": user_name,
  215. "publish_time_stamp": publish_time_stamp,
  216. "publish_time_str": publish_time_str,
  217. "update_time_stamp": int(time.time()),
  218. "video_width": int(video_obj.get("w", 0)),
  219. "video_height": int(video_obj.get("h", 0)),
  220. "avatar_url": video_obj.get("user", {}).get("hurl", ""),
  221. "profile_id": video_obj["id"],
  222. "profile_mid": video_obj.get("user", {}).get("mid", ""),
  223. "cover_url": video_obj.get("url", ""),
  224. "video_url": video_obj.get("v_url", ""),
  225. "session": f"xiaoniangao-author-{int(time.time())}",
  226. "out_user_id": video_obj["id"],
  227. "platform": self.platform,
  228. "strategy": self.mode,
  229. "out_video_id": video_obj.get("vid", ""),
  230. }
  231. for k, v in video_dict.items():
  232. Common.logger(self.mode, self.platform).info(f"{k}:{v}")
  233. pipeline = PiaoQuanPipeline(
  234. platform=self.platform,
  235. mode=self.mode,
  236. rule_dict=self.rule_dict,
  237. env=self.env,
  238. item=video_dict,
  239. trace_id=trace_id,
  240. )
  241. flag = pipeline.process_item()
  242. if flag:
  243. video_dict["width"] = video_dict["video_width"]
  244. video_dict["height"] = video_dict["video_height"]
  245. video_dict["crawler_rule"] = json.dumps(self.rule_dict)
  246. video_dict["user_id"] = user_dict["uid"]
  247. video_dict["publish_time"] = video_dict["publish_time_str"]
  248. # print(video_dict)
  249. self.mq.send_msg(video_dict)
  250. self.download_count += 1
  251. AliyunLogger.logging(
  252. code="1002",
  253. platform=self.platform,
  254. mode=self.mode,
  255. env=self.env,
  256. data=video_dict,
  257. trace_id=trace_id,
  258. message="成功发送 MQ 至 ETL",
  259. )
  260. Common.logging(
  261. log_type=self.mode,
  262. crawler=self.platform,
  263. env=self.env,
  264. message="成功发送 MQ 至 ETL",
  265. )
  266. # if __name__ == "__main__":
  267. # XNGA = XiaoNianGaoAuthor(
  268. # platform="xiaoniangao",
  269. # mode="author",
  270. # rule_dict={},
  271. # env="prod",
  272. # user_list=[{"link": 295640510, "uid": "12334"}],
  273. # )
  274. # XNGA.get_author_list()