haokan_follow.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/1/13
  4. import datetime
  5. import os
  6. import sys
  7. import time
  8. import requests
  9. import urllib3
  10. sys.path.append(os.getcwd())
  11. from main.common import Common
  12. from main.feishu_lib import Feishu
  13. from main.haokan_publish import Publish
  14. class Follow:
  15. ctime = ''
  16. @classmethod
  17. def filter_words(cls, log_type):
  18. try:
  19. filter_words_sheet = Feishu.get_values_batch(log_type, 'haokan', 'nKgHzp')
  20. filter_words_list = []
  21. for x in filter_words_sheet:
  22. for y in x:
  23. if y is None:
  24. pass
  25. else:
  26. filter_words_list.append(y)
  27. return filter_words_list
  28. except Exception as e:
  29. Common.logger(log_type).error(f'filter_words异常:{e}')
  30. @classmethod
  31. def get_users_from_feishu(cls, log_type):
  32. try:
  33. user_sheet = Feishu.get_values_batch(log_type, 'haokan', 'x4nb7H')
  34. user_dict = {}
  35. for i in range(1, len(user_sheet)):
  36. user_name = user_sheet[i][0]
  37. out_id = user_sheet[i][1]
  38. our_id = user_sheet[i][3]
  39. if user_name is None or out_id is None or our_id is None:
  40. pass
  41. else:
  42. user_dict[user_name] = str(out_id) + ',' + str(our_id)
  43. return user_dict
  44. except Exception as e:
  45. Common.logger(log_type).error(f'get_users_from_feishu异常:{e}\n')
  46. @classmethod
  47. def follow_download_rule(cls, duration, width, height):
  48. if int(duration) >= 60:
  49. if int(width) >= 720 or int(height) >= 720:
  50. return True
  51. else:
  52. return False
  53. else:
  54. return False
  55. @classmethod
  56. def get_follow_feed(cls, log_type, out_id, our_id, user_name, env):
  57. try:
  58. while True:
  59. url = 'https://haokan.baidu.com/web/author/listall?'
  60. headers = {
  61. 'Accept': '*/*',
  62. 'Accept-Encoding': 'gzip, deflate, br',
  63. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  64. 'Cache-Control': 'no-cache',
  65. 'Connection': 'keep-alive',
  66. 'Content-Type': 'application/x-www-form-urlencoded',
  67. 'Cookie': Feishu.get_values_batch(log_type, 'haokan', '5LksMx')[0][0],
  68. 'Referer': 'https://haokan.baidu.com/author/'+str(out_id),
  69. 'Pragma': 'no-cache',
  70. 'Host': 'haokan.baidu.com',
  71. 'sec-ch-ua': '"Not?A_Brand";v="8", "Chromium";v="108", "Microsoft Edge";v="108"',
  72. 'sec-ch-ua-mobile': '?0',
  73. 'sec-ch-ua-platform': '"macOS"',
  74. 'Sec-Fetch-Dest': 'empty',
  75. 'Sec-Fetch-Mode': 'cors',
  76. 'Sec-Fetch-Site': 'same-origin',
  77. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.76'
  78. }
  79. params = {
  80. 'app_id': str(out_id),
  81. 'ctime': cls.ctime,
  82. 'rn': '10',
  83. 'searchAfter': '',
  84. '_api': '1'
  85. }
  86. response = requests.get(url=url, headers=headers, params=params, verify=False)
  87. if '"errno":0,' not in response.text:
  88. Common.logger(log_type).warning(f'get_follow_feed:{response.text}\n')
  89. elif len(response.json()['data']['results']) == 0:
  90. Common.logger(log_type).info(f'get_follow_feed:{response.json()}\n')
  91. cls.ctime = 0
  92. else:
  93. cls.ctime = response.json()['data']['ctime']
  94. follow_feeds = response.json()['data']['results']
  95. for i in range(len(follow_feeds)):
  96. # video_title
  97. if 'title' not in follow_feeds[i]['content']:
  98. video_title = ''
  99. else:
  100. video_title = follow_feeds[i]['content']['title']
  101. # video_id
  102. if 'vid' not in follow_feeds[i]['content']:
  103. video_id = ''
  104. else:
  105. video_id = follow_feeds[i]['content']['vid']
  106. # is_top
  107. if 'is_show_feature' not in follow_feeds[i]['content']:
  108. is_top = ''
  109. else:
  110. is_top = follow_feeds[i]['content']['is_show_feature']
  111. # play_cnt
  112. if 'playcnt' not in follow_feeds[i]['content']:
  113. play_cnt = ''
  114. else:
  115. play_cnt = follow_feeds[i]['content']['playcnt']
  116. # duration
  117. if 'duration' not in follow_feeds[i]['content']:
  118. duration = ''
  119. duration_stamp = ''
  120. else:
  121. duration = follow_feeds[i]['content']['duration']
  122. duration_stamp = int(duration.split(':')[0])*60 + int(duration.split(':')[-1])
  123. # publish_time
  124. if 'publish_time' not in follow_feeds[i]['content']:
  125. publish_time = ''
  126. else:
  127. publish_time = follow_feeds[i]['content']['publish_time']
  128. # publish_time_stamp
  129. if '刚刚' in publish_time:
  130. publish_time_stamp = int(time.time())
  131. elif '分钟前' in publish_time:
  132. publish_time_stamp = int(time.time()) - int(publish_time[0]) * 60
  133. elif '小时前' in publish_time:
  134. publish_time_stamp = int(time.time()) - int(publish_time[0]) * 3600
  135. elif '昨天' in publish_time:
  136. publish_time_str = (datetime.date.today() + datetime.timedelta(days=-1)).strftime("%Y/%m/%d")
  137. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y/%m/%d")))
  138. elif '天前' in publish_time:
  139. today = datetime.date.today()
  140. publish_time_str = today - datetime.timedelta(days=int(publish_time[0]))
  141. publish_time_stamp = int(time.mktime(publish_time_str.timetuple()))
  142. elif '年' in publish_time:
  143. publish_time_str = publish_time.replace('年', '/').replace('月', '/').replace('日', '')
  144. publish_time_stamp = int(time.mktime(time.strptime(publish_time_str, "%Y/%m/%d")))
  145. else:
  146. publish_time_str = publish_time.replace('月', '/').replace('日', '')
  147. this_year = datetime.datetime.now().year
  148. publish_time_stamp = int(time.mktime(time.strptime(f"{this_year}/{publish_time_str}", "%Y/%m/%d")))
  149. # cover_url
  150. if 'cover_src' in follow_feeds[i]['content']:
  151. cover_url = follow_feeds[i]['content']['cover_src']
  152. elif 'cover_src_pc' in follow_feeds[i]['content']:
  153. cover_url = follow_feeds[i]['content']['cover_src_pc']
  154. elif 'poster' in follow_feeds[i]['content']:
  155. cover_url = follow_feeds[i]['content']['poster']
  156. else:
  157. cover_url = ''
  158. if is_top is True and int(time.time()) - publish_time_stamp >= 3600*24*30:
  159. Common.logger(log_type).info(f'video_title:{video_title}')
  160. Common.logger(log_type).info(f'置顶视频,发布时间超过30天:{publish_time}\n')
  161. elif int(time.time()) - publish_time_stamp >= 3600*24*30:
  162. Common.logger(log_type).info(f'video_title:{video_title}')
  163. Common.logger(log_type).info(f'发布时间超过30天:{publish_time}\n')
  164. cls.ctime = ''
  165. return
  166. else:
  167. video_info_dict = cls.get_video_url(log_type, video_id)
  168. # video_url
  169. video_url = video_info_dict['video_url']
  170. # video_width
  171. video_width = video_info_dict['video_width']
  172. # video_height
  173. video_height = video_info_dict['video_height']
  174. Common.logger(log_type).info(f'video_title:{video_title}')
  175. # Common.logger(log_type).info(f'user_name:{user_name}')
  176. # Common.logger(log_type).info(f'out_id:{out_id}')
  177. # Common.logger(log_type).info(f'our_id:{our_id}')
  178. # Common.logger(log_type).info(f'duration_stamp:{duration_stamp}')
  179. Common.logger(log_type).info(f'duration:{duration}')
  180. Common.logger(log_type).info(f'video_width:{video_width}')
  181. Common.logger(log_type).info(f'video_height:{video_height}')
  182. Common.logger(log_type).info(f'publish_time:{publish_time}')
  183. Common.logger(log_type).info(f'video_url:{video_url}\n')
  184. video_dict = {
  185. 'video_title': video_title,
  186. 'video_id': video_id,
  187. 'play_cnt': play_cnt,
  188. 'duration': duration,
  189. 'duration_stamp': duration_stamp,
  190. 'publish_time': publish_time,
  191. 'video_width': video_width,
  192. 'video_height': video_height,
  193. 'user_name': user_name,
  194. 'cover_url': cover_url,
  195. 'video_url': video_url
  196. }
  197. cls.download_publish(log_type, video_dict, our_id, env)
  198. except Exception as e:
  199. Common.logger(log_type).error(f'get_follow_feed异常:{e}\n')
  200. @classmethod
  201. def get_video_url(cls, log_type, video_id):
  202. try:
  203. url = 'https://haokan.hao123.com/v?'
  204. params = {
  205. 'vid': str(video_id),
  206. '_format': 'json',
  207. }
  208. headers = {
  209. 'Accept': '*/*',
  210. 'Accept-Encoding': 'gzip, deflate, br',
  211. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  212. 'Cache-Control': 'no-cache',
  213. 'Connection': 'keep-alive',
  214. 'Content-Type': 'application/x-www-form-urlencoded',
  215. 'Cookie': 'PC_TAB_LOG=video_details_page; COMMON_LID=b0be69dd9fcae328d06935bd40f615cd; Hm_lvt_4aadd610dfd2f5972f1efee2653a2bc5=1669029953; hkpcvideolandquery=%u82CF%u5DDE%u6700%u5927%u7684%u4E8C%u624B%u8F66%u8D85%u5E02%uFF0C%u8F6C%u4E00%u8F6C%u91CC%u8FB9%u8C6A%u8F66%u592A%u591A%u4E86%uFF0C%u4EF7%u683C%u66F4%u8BA9%u6211%u5403%u60CA%uFF01; Hm_lpvt_4aadd610dfd2f5972f1efee2653a2bc5=1669875695; ariaDefaultTheme=undefined; reptileData=%7B%22data%22%3A%22636c55e0319da5169a60acec4a264a35c10862f8abfe2f2cc32c55eb6b0ab4de0efdfa115ea522d6d4d361dea07feae2831d3e2c16ed6b051c611ffe5aded6c9f852501759497b9fbd2132a2160e1e40e5845b41f78121ddcc3288bd077ae4e8%22%2C%22key_id%22%3A%2230%22%2C%22sign%22%3A%22f6752aac%22%7D; RT="z=1&dm=hao123.com&si=uc0q7wnm4w&ss=lb4otu71&sl=j&tt=av0&bcn=https%3A%2F%2Ffclog.baidu.com%2Flog%2Fweirwood%3Ftype%3Dperf&ld=1rdw&cl=7v6c"',
  216. 'Pragma': 'no-cache',
  217. 'Referer': 'https://haokan.hao123.com/v?vid=10623278258033022286&pd=pc&context=',
  218. 'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
  219. 'sec-ch-ua-mobile': '?0',
  220. 'sec-ch-ua-platform': '"macOS"',
  221. 'Sec-Fetch-Dest': 'empty',
  222. 'Sec-Fetch-Mode': 'cors',
  223. 'Sec-Fetch-Site': 'same-origin',
  224. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
  225. }
  226. urllib3.disable_warnings()
  227. r = requests.get(url=url, headers=headers, params=params, verify=False)
  228. if r.status_code != 200:
  229. video_url = ''
  230. video_width = ''
  231. video_height = ''
  232. Common.logger(log_type).info(f'get_video_url_response:{r.text}')
  233. elif r.json()['errno'] != 0 or len(r.json()['data']) == 0:
  234. video_url = ''
  235. video_width = ''
  236. video_height = ''
  237. Common.logger(log_type).info(f'get_video_url_response:{r.json()}')
  238. else:
  239. clarityUrl = r.json()['data']['apiData']['curVideoMeta']['clarityUrl']
  240. video_url = r.json()['data']['apiData']['curVideoMeta']['clarityUrl'][len(clarityUrl) - 1]['url']
  241. video_width = r.json()['data']['apiData']['curVideoMeta']['clarityUrl'][len(clarityUrl) - 1]['vodVideoHW'].split('$$')[-1]
  242. video_height = r.json()['data']['apiData']['curVideoMeta']['clarityUrl'][len(clarityUrl) - 1]['vodVideoHW'].split('$$')[0]
  243. video_info_dict = {
  244. 'video_url': video_url,
  245. 'video_width': video_width,
  246. 'video_height': video_height
  247. }
  248. return video_info_dict
  249. except Exception as e:
  250. Common.logger(log_type).error(f'get_video_url异常:{e}\n')
  251. @classmethod
  252. def download_publish(cls, log_type, video_dict, our_id, env):
  253. try:
  254. if video_dict['video_title'] == '' or video_dict['video_id'] == '' or video_dict['video_url'] == '':
  255. Common.logger(log_type).info('无效视频\n')
  256. elif int(video_dict['duration_stamp']) < 60:
  257. Common.logger(log_type).info(f'时长:{int(video_dict["duration"])} < 60s\n')
  258. elif int(video_dict['video_width']) < 720 or int(video_dict['video_height']) < 720:
  259. Common.logger(log_type).info(f'{int(video_dict["video_width"])}*{int(video_dict["video_height"])} < 720P\n')
  260. elif any(word if word in video_dict['video_title'] else False for word in cls.filter_words(log_type)) is True:
  261. Common.logger(log_type).info('已中过滤词库\n')
  262. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, 'haokan', '5pWipX') for x in y]:
  263. Common.logger(log_type).info('视频已下载\n')
  264. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, 'haokan', '7f05d8') for x in y]:
  265. Common.logger(log_type).info('视频已下载\n')
  266. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, 'haokan', 'kVaSjf') for x in y]:
  267. Common.logger(log_type).info('视频已下载\n')
  268. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, 'haokan', 'A5VCbq') for x in y]:
  269. Common.logger(log_type).info('视频已下载\n')
  270. else:
  271. # 下载
  272. Common.download_method(log_type, 'cover', video_dict['video_title'], video_dict['cover_url'])
  273. Common.download_method(log_type, 'video', video_dict['video_title'], video_dict['video_url'])
  274. with open("./videos/" + video_dict['video_title']
  275. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  276. f_a.write(str(video_dict['video_id']) + "\n" +
  277. str(video_dict['video_title']) + "\n" +
  278. str(video_dict['duration_stamp']) + "\n" +
  279. '100000' + "\n" +
  280. '100000' + "\n" +
  281. '100000' + "\n" +
  282. '100000' + "\n" +
  283. '1920*1080' + "\n" +
  284. str(int(time.time())) + "\n" +
  285. str(video_dict['user_name']) + "\n" +
  286. str(video_dict['cover_url']) + "\n" +
  287. str(video_dict['video_url']) + "\n" +
  288. str(video_dict['cover_url']) + "\n" +
  289. "HAOKAN" + str(int(time.time())))
  290. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  291. # 上传
  292. Common.logger(log_type).info(f"开始上传视频:{video_dict['video_title']}")
  293. if env == 'dev':
  294. our_video_id = Publish.upload_and_publish(log_type, our_id, env)
  295. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  296. else:
  297. our_video_id = Publish.upload_and_publish(log_type, our_id, env)
  298. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  299. Common.logger(log_type).info(f"视频上传完成:{video_dict['video_title']}\n")
  300. # 保存视频信息至云文档
  301. Common.logger(log_type).info(f"保存视频至已下载表:{video_dict['video_title']}")
  302. Feishu.insert_columns(log_type, "haokan", "kVaSjf", "ROWS", 1, 2)
  303. upload_time = int(time.time())
  304. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  305. '定向榜',
  306. video_dict['video_title'],
  307. video_dict['video_id'],
  308. our_video_link,
  309. int(video_dict['play_cnt']),
  310. video_dict['duration'],
  311. video_dict['publish_time'],
  312. video_dict['video_width']+"*"+video_dict['video_height'],
  313. video_dict['user_name'],
  314. video_dict['cover_url'],
  315. video_dict['video_url']]]
  316. time.sleep(1)
  317. Feishu.update_values(log_type, "haokan", "kVaSjf", "F2:Z2", values)
  318. Common.logger(log_type).info(f"视频:{video_dict['video_title']},下载/上传成功\n")
  319. except Exception as e:
  320. Common.logger(log_type).error(f'download_publish异常:{e}\n')
  321. @classmethod
  322. def get_user_videos(cls, log_type, env):
  323. try:
  324. user_dict = cls.get_users_from_feishu(log_type)
  325. if len(user_dict) == 0:
  326. Common.logger(log_type).warning('用户ID列表为空\n')
  327. else:
  328. for k, v in user_dict.items():
  329. user_name = k
  330. out_id = v.split(',')[0]
  331. our_id = v.split(',')[1]
  332. Common.logger(log_type).info(f'抓取{user_name}主页视频\n')
  333. cls.get_follow_feed(log_type, out_id, our_id, user_name, env)
  334. Common.logger(log_type).info('休眠 30 秒\n')
  335. time.sleep(30)
  336. cls.ctime = ''
  337. except Exception as e:
  338. Common.logger(log_type).error(f'get_user_videos异常:{e}\n')
  339. if __name__ == '__main__':
  340. print(Follow.get_users_from_feishu('follow'))
  341. pass