haokan_channel.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2022/11/23
  4. import os
  5. import sys
  6. import time
  7. import requests
  8. import urllib3
  9. sys.path.append(os.getcwd())
  10. from main.common import Common
  11. from main.feishu_lib import Feishu
  12. from main.haokan_publish import Publish
  13. from main.get_cookies import GetCookies
  14. class Channel:
  15. @classmethod
  16. def download_rule(cls, play_cnt, duration):
  17. if int(play_cnt) >= 50000:
  18. if int(duration) >= 60:
  19. return True
  20. else:
  21. return False
  22. else:
  23. return False
  24. @classmethod
  25. def get_channel_from_feishu(cls, log_type):
  26. try:
  27. user_sheet = Feishu.get_values_batch(log_type, 'haokan', 'TaQXk3')
  28. user_dict = {}
  29. for i in range(1, len(user_sheet)):
  30. user_name = user_sheet[i][0]
  31. out_id = user_sheet[i][1]
  32. our_id = user_sheet[i][3]
  33. if user_name is None or out_id is None or our_id is None or i == 13:
  34. pass
  35. else:
  36. user_dict[user_name] = str(out_id) + ',' + str(our_id)
  37. return user_dict
  38. except Exception as e:
  39. Common.logger(log_type).error(f'get_tab_from_feishu异常:{e}\n')
  40. @classmethod
  41. def get_channel_feeds(cls, log_type, tab, cookies):
  42. try:
  43. url = "https://haokan.baidu.com/web/video/feed?"
  44. params = {
  45. 'tab': str(tab),
  46. 'act': 'pcFeed',
  47. 'pd': 'pc',
  48. 'num': '20',
  49. 'shuaxin_id': '16698987960000',
  50. }
  51. headers = {
  52. 'Accept': '*/*',
  53. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  54. 'Cache-Control': 'no-cache',
  55. 'Connection': 'keep-alive',
  56. 'Content-Type': 'application/x-www-form-urlencoded',
  57. 'Cookie': str(cookies).strip().replace('\n', ''),
  58. 'Pragma': 'no-cache',
  59. 'Referer': 'https://haokan.baidu.com/tab/recommend',
  60. 'Sec-Fetch-Dest': 'empty',
  61. 'Sec-Fetch-Mode': 'cors',
  62. 'Sec-Fetch-Site': 'same-origin',
  63. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '
  64. 'AppleWebKit/537.36 (KHTML, like Gecko) '
  65. 'Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.52',
  66. 'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
  67. 'sec-ch-ua-mobile': '?0',
  68. 'sec-ch-ua-platform': '"macOS"'
  69. }
  70. urllib3.disable_warnings()
  71. r = requests.get(url=url, headers=headers, params=params, verify=False)
  72. if r.json()['errno'] != 0 or r.json()['errmsg'] != '成功':
  73. Common.logger(log_type).error(f'feeds_response:{r.json()}\n')
  74. elif len(r.json()['data']['response']['videos']) == 0:
  75. Common.logger(log_type).warning(f'feeds_response:{r.json()}\n')
  76. else:
  77. feeds = r.json()['data']['response']['videos']
  78. return feeds
  79. except Exception as e:
  80. Common.logger(log_type).error(f'get_channel_feeds异常:{e}\n')
  81. @classmethod
  82. def get_video_url(cls, log_type, video_id, cookies):
  83. try:
  84. url = 'https://haokan.hao123.com/v?'
  85. params = {
  86. 'vid': str(video_id),
  87. '_format': 'json',
  88. }
  89. headers = {
  90. 'Accept': '*/*',
  91. 'Accept-Encoding': 'gzip, deflate, br',
  92. 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  93. 'Cache-Control': 'no-cache',
  94. 'Connection': 'keep-alive',
  95. 'Content-Type': 'application/x-www-form-urlencoded',
  96. 'Cookie': str(cookies).strip().replace('\n', ''),
  97. 'Pragma': 'no-cache',
  98. 'Referer': 'https://haokan.hao123.com/v?vid='+str(video_id)+'&pd=pc&context=',
  99. 'sec-ch-ua': '"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
  100. 'sec-ch-ua-mobile': '?0',
  101. 'sec-ch-ua-platform': '"macOS"',
  102. 'Sec-Fetch-Dest': 'empty',
  103. 'Sec-Fetch-Mode': 'cors',
  104. 'Sec-Fetch-Site': 'same-origin',
  105. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) '
  106. 'AppleWebKit/537.36 (KHTML, like Gecko) '
  107. 'Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.62',
  108. }
  109. r = requests.get(url=url, headers=headers, params=params, verify=False)
  110. if r.status_code != 200:
  111. Common.logger(log_type).info(f'get_video_url_response:{r.text}')
  112. elif r.json()['errno'] != 0 or len(r.json()['data']) == 0:
  113. Common.logger(log_type).info(f'get_video_url_response:{r.json()}')
  114. else:
  115. clarityUrl = r.json()['data']['apiData']['curVideoMeta']['clarityUrl']
  116. video_url = r.json()['data']['apiData']['curVideoMeta']['clarityUrl'][len(clarityUrl) - 1]['url']
  117. return video_url
  118. except Exception as e:
  119. Common.logger(log_type).info(f'get_video_url异常:{e}\n')
  120. @classmethod
  121. def get_channel_videos(cls, log_type, tab, our_id, env, cookies):
  122. try:
  123. feeds = cls.get_channel_feeds(log_type, tab, cookies)
  124. for i in range(len(feeds)):
  125. # video_title
  126. if 'title' not in feeds[i]:
  127. video_title = 0
  128. else:
  129. video_title = feeds[i]['title']
  130. # video_id
  131. if 'id' not in feeds[i]:
  132. video_id = 0
  133. else:
  134. video_id = feeds[i]['id']
  135. # play_cnt
  136. if 'playcnt' not in feeds[i]:
  137. play_cnt = 0
  138. else:
  139. play_cnt = feeds[i]['playcnt']
  140. # duration
  141. if 'duration' not in feeds[i]:
  142. duration = 0
  143. else:
  144. duration = int(feeds[i]['duration'].split(':')[0])*60 + int(feeds[i]['duration'].split(':')[-1])
  145. # publish_time
  146. if 'publish_time' not in feeds[i]:
  147. publish_time = 0
  148. else:
  149. publish_time = feeds[i]['publish_time']
  150. # user_name
  151. if 'source_name' not in feeds[i]:
  152. user_name = 0
  153. else:
  154. user_name = feeds[i]['source_name']
  155. # head_url
  156. if 'author_avatar' not in feeds[i]:
  157. head_url = 0
  158. else:
  159. head_url = feeds[i]['author_avatar']
  160. # cover_url
  161. if 'poster_big' in feeds[i]:
  162. cover_url = feeds[i]['poster_big']
  163. elif 'poster_pc' in feeds[i]:
  164. cover_url = feeds[i]['poster_pc']
  165. elif 'poster_small' in feeds[i]:
  166. cover_url = feeds[i]['poster_small']
  167. else:
  168. cover_url = 0
  169. # video_url
  170. get_video_url = cls.get_video_url(log_type, video_id, cookies)
  171. if get_video_url is not None:
  172. video_url = get_video_url
  173. elif 'play_url' in feeds[i]:
  174. video_url = feeds[i]['play_url']
  175. else:
  176. video_url = 0
  177. Common.logger(log_type).info(f'video_title:{video_title}')
  178. Common.logger(log_type).info(f'play_cnt:{play_cnt}')
  179. Common.logger(log_type).info(f'duration:{duration}')
  180. Common.logger(log_type).info(f'video_url:{video_url}')
  181. video_dict = {'video_title': video_title,
  182. 'video_id': video_id,
  183. 'play_cnt': play_cnt,
  184. 'duration': duration,
  185. 'publish_time': publish_time,
  186. 'user_name': user_name,
  187. 'head_url': head_url,
  188. 'cover_url': cover_url,
  189. 'video_url': video_url}
  190. cls.download_publish(log_type, tab, our_id, video_dict, env)
  191. except Exception as e:
  192. Common.logger(log_type).error(f'get_channel_videos异常:{e}\n')
  193. @classmethod
  194. def download_publish(cls, log_type, tab, our_id, video_dict, env):
  195. try:
  196. if video_dict['video_title'] == 0 or video_dict['video_url'] == 0:
  197. Common.logger(log_type).info('无效视频\n')
  198. elif cls.download_rule(video_dict['play_cnt'], video_dict['duration']) is False:
  199. Common.logger(log_type).info('不满足抓取规则\n')
  200. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(
  201. log_type, 'haokan', '5pWipX') for x in y]:
  202. Common.logger(log_type).info('视频已下载\n')
  203. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(
  204. log_type, 'haokan', '7f05d8') for x in y]:
  205. Common.logger(log_type).info('视频已下载\n')
  206. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(
  207. log_type, 'haokan', 'A5VCbq') for x in y]:
  208. Common.logger(log_type).info('视频已下载\n')
  209. else:
  210. # 下载
  211. Common.download_method(log_type, 'cover', video_dict['video_title'], video_dict['cover_url'])
  212. Common.download_method(log_type, 'video', video_dict['video_title'], video_dict['video_url'])
  213. with open("./videos/" + video_dict['video_title']
  214. + "/" + "info.txt", "a", encoding="UTF-8") as f_a:
  215. f_a.write(str(video_dict['video_id']) + "\n" +
  216. str(video_dict['video_title']) + "\n" +
  217. str(video_dict['duration']) + "\n" +
  218. '0' + "\n" +
  219. '0' + "\n" +
  220. '0' + "\n" +
  221. '0' + "\n" +
  222. '1920*1080' + "\n" +
  223. str(int(time.time())) + "\n" +
  224. str(video_dict['user_name']) + "\n" +
  225. str(video_dict['head_url']) + "\n" +
  226. str(video_dict['video_url']) + "\n" +
  227. str(video_dict['cover_url']) + "\n" +
  228. "HAOKAN" + str(int(time.time())))
  229. Common.logger(log_type).info("==========视频信息已保存至info.txt==========")
  230. # 上传
  231. Common.logger(log_type).info(f"开始上传视频:{video_dict['video_title']}")
  232. if env == 'dev':
  233. our_video_id = Publish.upload_and_publish(log_type, our_id, env)
  234. our_video_link = "https://testadmin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  235. else:
  236. our_video_id = Publish.upload_and_publish(log_type, our_id, env)
  237. our_video_link = "https://admin.piaoquantv.com/cms/post-detail/" + str(our_video_id) + "/info"
  238. Common.logger(log_type).info(f"视频上传完成:{video_dict['video_title']}\n")
  239. # 保存视频信息至云文档
  240. Common.logger(log_type).info(f"保存视频至已下载表:{video_dict['video_title']}")
  241. Feishu.insert_columns(log_type, "haokan", "7f05d8", "ROWS", 1, 2)
  242. upload_time = int(time.time())
  243. if tab == 'recommend':
  244. tab = '播放量榜_首页频道'
  245. elif tab == 'yinyue_new':
  246. tab = '播放量榜_音乐频道'
  247. elif tab == 'gaoxiao_new':
  248. tab = '播放量榜_搞笑频道'
  249. elif tab == 'zongyi_new':
  250. tab = '播放量榜_综艺频道'
  251. elif tab == 'shenghuo_new':
  252. tab = '播放量榜_生活频道'
  253. elif tab == 'meishi_new':
  254. tab = '播放量榜_美食频道'
  255. elif tab == 'sannong_new':
  256. tab = '播放量榜_三农频道'
  257. elif tab == 'junshi_new':
  258. tab = '播放量榜_军事频道'
  259. elif tab == 'shehui_new':
  260. tab = '播放量榜_社会频道'
  261. elif tab == 'keji_new':
  262. tab = '播放量榜_科技频道'
  263. elif tab == 'wenhua_new':
  264. tab = '播放量榜_文化频道'
  265. elif tab == 'lvyou_new':
  266. tab = '播放量榜_旅游频道'
  267. else:
  268. tab = '播放量榜'
  269. values = [[time.strftime("%Y/%m/%d %H:%M:%S", time.localtime(upload_time)),
  270. tab,
  271. video_dict['video_title'],
  272. video_dict['video_id'],
  273. our_video_link,
  274. int(video_dict['play_cnt']),
  275. video_dict['duration'],
  276. video_dict['publish_time'],
  277. video_dict['user_name'],
  278. video_dict['head_url'],
  279. video_dict['cover_url'],
  280. video_dict['video_url']]]
  281. time.sleep(1)
  282. Feishu.update_values(log_type, "haokan", "7f05d8", "F2:Z2", values)
  283. Common.logger(log_type).info(f"视频:{video_dict['video_title']},下载/上传成功\n")
  284. except Exception as e:
  285. Common.logger(log_type).error(f'download_publish异常:{e}\n')
  286. @classmethod
  287. def get_all_channel_videos(cls, log_type, env):
  288. try:
  289. channel_dict = cls.get_channel_from_feishu(log_type)
  290. if len(channel_dict) == 0:
  291. Common.logger(log_type).warning('频道数量为空\n')
  292. else:
  293. for k, v in channel_dict.items():
  294. Common.logger(log_type).info(f'正在获取 {k} 频道视频\n')
  295. cookies = GetCookies.get_cookies(v.split(',')[0])
  296. Common.logger(log_type).info(f'cookies:{cookies}\n')
  297. cls.get_channel_videos(log_type, v.split(',')[0], v.split(',')[1], env, cookies)
  298. time.sleep(10)
  299. except Exception as e:
  300. Common.logger(log_type).error(f'get_all_channel_videos异常:{e}\n')
  301. if __name__ == '__main__':
  302. channel_cookies = GetCookies.get_cookies('recommend')
  303. Channel.get_channel_videos('channel', 'lvyou_new', '6267140', 'dev', channel_cookies)
  304. pass