xigua_recommend.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/4/7
  4. import base64
  5. import json
  6. import os
  7. import random
  8. import string
  9. import sys
  10. import time
  11. import requests
  12. import urllib3
  13. from requests.adapters import HTTPAdapter
  14. from selenium import webdriver
  15. from selenium.webdriver import DesiredCapabilities
  16. from selenium.webdriver.chrome.service import Service
  17. sys.path.append(os.getcwd())
  18. from common.common import Common
  19. from common.feishu import Feishu
  20. class XiguaRecommend:
  21. @classmethod
  22. def random_signature(cls):
  23. src_digits = string.digits # string_数字
  24. src_uppercase = string.ascii_uppercase # string_大写字母
  25. src_lowercase = string.ascii_lowercase # string_小写字母
  26. digits_num = random.randint(1, 6)
  27. uppercase_num = random.randint(1, 26 - digits_num - 1)
  28. lowercase_num = 26 - (digits_num + uppercase_num)
  29. password = random.sample(src_digits, digits_num) + random.sample(src_uppercase, uppercase_num) + random.sample(
  30. src_lowercase, lowercase_num)
  31. random.shuffle(password)
  32. new_password = 'AAAAAAAAAA' + ''.join(password)[10:-4] + 'AAAB'
  33. new_password_start = new_password[0:18]
  34. new_password_end = new_password[-7:]
  35. if new_password[18] == '8':
  36. new_password = new_password_start + 'w' + new_password_end
  37. elif new_password[18] == '9':
  38. new_password = new_password_start + 'x' + new_password_end
  39. elif new_password[18] == '-':
  40. new_password = new_password_start + 'y' + new_password_end
  41. elif new_password[18] == '.':
  42. new_password = new_password_start + 'z' + new_password_end
  43. else:
  44. new_password = new_password_start + 'y' + new_password_end
  45. return new_password
  46. @classmethod
  47. def get_signature(cls, env):
  48. # try:
  49. # time1 = time.time()
  50. # print(f"time1:{time1}")
  51. # 打印请求配置
  52. ca = DesiredCapabilities.CHROME
  53. ca["goog:loggingPrefs"] = {"performance": "ALL"}
  54. # 不打开浏览器运行
  55. chrome_options = webdriver.ChromeOptions()
  56. chrome_options.add_argument("headless")
  57. chrome_options.add_argument(
  58. f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')
  59. chrome_options.add_argument("--no-sandbox")
  60. # driver初始化
  61. if env == "dev":
  62. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options,
  63. service=Service('/Users/wangkun/Downloads/chromedriver/chromedriver_v111/chromedriver'))
  64. else:
  65. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
  66. driver.implicitly_wait(10)
  67. driver.get('https://www.ixigua.com/')
  68. time.sleep(1)
  69. # 向上滑动 1000 个像素
  70. driver.execute_script('window.scrollBy(0, 2000)')
  71. # Common.logger(log_type, crawler).info('刷新页面')
  72. driver.refresh()
  73. logs = driver.get_log("performance")
  74. # Common.logger(log_type, crawler).info('已获取logs:{}\n', logs)
  75. driver.quit()
  76. for line in logs:
  77. msg = json.loads(line['message'])
  78. if 'params' not in msg['message']:
  79. pass
  80. elif 'documentURL' not in msg['message']['params']:
  81. pass
  82. elif 'www.ixigua.com' not in msg['message']['params']['documentURL']:
  83. pass
  84. elif 'url' not in msg['message']['params']['request']:
  85. pass
  86. elif '_signature' not in msg['message']['params']['request']['url']:
  87. pass
  88. else:
  89. url = msg['message']['params']['request']['url']
  90. signature = url.split('_signature=')[-1].split('&')[0]
  91. # print(f"url:{url}")
  92. # print(f"signature:{signature}")
  93. time2 = time.time()
  94. # print(f"time2:{time2}")
  95. # print(f"duration:{time2-time1}")
  96. return signature
  97. # except Exception as e:
  98. # Common.logger(log_type, crawler).error(f'get_signature异常:{e}\n')
  99. # 获取视频详情
  100. @classmethod
  101. def get_video_url(cls, log_type, crawler, gid):
  102. try:
  103. url = 'https://www.ixigua.com/api/mixVideo/information?'
  104. headers = {
  105. "accept-encoding": "gzip, deflate",
  106. "accept-language": "zh-CN,zh-Hans;q=0.9",
  107. "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
  108. "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15",
  109. "referer": "https://www.ixigua.com/7102614741050196520?logTag=0531c88ac04f38ab2c62",
  110. }
  111. params = {
  112. 'mixId': gid,
  113. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfC'
  114. 'NVVIOBNjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  115. 'X-Bogus': 'DFSzswVupYTANCJOSBk0P53WxM-r',
  116. '_signature': '_02B4Z6wo0000119LvEwAAIDCuktNZ0y5wkdfS7jAALThuOR8D9yWNZ.EmWHKV0WSn6Px'
  117. 'fPsH9-BldyxVje0f49ryXgmn7Tzk-swEHNb15TiGqa6YF.cX0jW8Eds1TtJOIZyfc9s5emH7gdWN94',
  118. }
  119. cookies = {
  120. 'ixigua-a-s': '1',
  121. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfCNVVIOB'
  122. 'NjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  123. 'ttwid': '1%7C_yXQeHWwLZgCsgHClOwTCdYSOt_MjdOkgnPIkpi-Sr8%7C1661241238%7Cf57d0c5ef3f1d7'
  124. '6e049fccdca1ac54887c34d1f8731c8e51a49780ff0ceab9f8',
  125. 'tt_scid': 'QZ4l8KXDG0YAEaMCSbADdcybdKbUfG4BC6S4OBv9lpRS5VyqYLX2bIR8CTeZeGHR9ee3',
  126. 'MONITOR_WEB_ID': '0a49204a-7af5-4e96-95f0-f4bafb7450ad',
  127. '__ac_nonce': '06304878000964fdad287',
  128. '__ac_signature': '_02B4Z6wo00f017Rcr3AAAIDCUVxeW1tOKEu0fKvAAI4cvoYzV-wBhq7B6D8k0no7lb'
  129. 'FlvYoinmtK6UXjRIYPXnahUlFTvmWVtb77jsMkKAXzAEsLE56m36RlvL7ky.M3Xn52r9t1IEb7IR3ke8',
  130. 'ttcid': 'e56fabf6e85d4adf9e4d91902496a0e882',
  131. '_tea_utm_cache_1300': 'undefined',
  132. 'support_avif': 'false',
  133. 'support_webp': 'false',
  134. 'xiguavideopcwebid': '7134967546256016900',
  135. 'xiguavideopcwebid.sig': 'xxRww5R1VEMJN_dQepHorEu_eAc',
  136. }
  137. urllib3.disable_warnings()
  138. s = requests.session()
  139. # max_retries=3 重试3次
  140. s.mount('http://', HTTPAdapter(max_retries=3))
  141. s.mount('https://', HTTPAdapter(max_retries=3))
  142. response = s.get(url=url, headers=headers, params=params, cookies=cookies, verify=False,
  143. proxies=Common.tunnel_proxies(), timeout=5)
  144. response.close()
  145. if 'data' not in response.json() or response.json()['data'] == '':
  146. Common.logger(log_type, crawler).warning('get_video_info: response: {}', response)
  147. else:
  148. video_info = response.json()['data']['gidInformation']['packerData']['video']
  149. video_url_dict = {}
  150. # video_url
  151. if 'videoResource' not in video_info:
  152. video_url_dict["video_url"] = ''
  153. video_url_dict["audio_url"] = ''
  154. video_url_dict["video_width"] = 0
  155. video_url_dict["video_height"] = 0
  156. elif 'dash_120fps' in video_info['videoResource']:
  157. if "video_list" in video_info['videoResource']['dash_120fps'] and 'video_4' in \
  158. video_info['videoResource']['dash_120fps']['video_list']:
  159. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_4'][
  160. 'backup_url_1']
  161. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_4'][
  162. 'backup_url_1']
  163. if len(video_url) % 3 == 1:
  164. video_url += '=='
  165. elif len(video_url) % 3 == 2:
  166. video_url += '='
  167. elif len(audio_url) % 3 == 1:
  168. audio_url += '=='
  169. elif len(audio_url) % 3 == 2:
  170. audio_url += '='
  171. video_url = base64.b64decode(video_url).decode('utf8')
  172. audio_url = base64.b64decode(audio_url).decode('utf8')
  173. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_4']['vwidth']
  174. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_4'][
  175. 'vheight']
  176. video_url_dict["video_url"] = video_url
  177. video_url_dict["audio_url"] = audio_url
  178. video_url_dict["video_width"] = video_width
  179. video_url_dict["video_height"] = video_height
  180. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_3' in \
  181. video_info['videoResource']['dash_120fps']['video_list']:
  182. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_3'][
  183. 'backup_url_1']
  184. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_3'][
  185. 'backup_url_1']
  186. if len(video_url) % 3 == 1:
  187. video_url += '=='
  188. elif len(video_url) % 3 == 2:
  189. video_url += '='
  190. elif len(audio_url) % 3 == 1:
  191. audio_url += '=='
  192. elif len(audio_url) % 3 == 2:
  193. audio_url += '='
  194. video_url = base64.b64decode(video_url).decode('utf8')
  195. audio_url = base64.b64decode(audio_url).decode('utf8')
  196. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_3']['vwidth']
  197. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_3'][
  198. 'vheight']
  199. video_url_dict["video_url"] = video_url
  200. video_url_dict["audio_url"] = audio_url
  201. video_url_dict["video_width"] = video_width
  202. video_url_dict["video_height"] = video_height
  203. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_2' in \
  204. video_info['videoResource']['dash_120fps']['video_list']:
  205. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_2'][
  206. 'backup_url_1']
  207. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_2'][
  208. 'backup_url_1']
  209. if len(video_url) % 3 == 1:
  210. video_url += '=='
  211. elif len(video_url) % 3 == 2:
  212. video_url += '='
  213. elif len(audio_url) % 3 == 1:
  214. audio_url += '=='
  215. elif len(audio_url) % 3 == 2:
  216. audio_url += '='
  217. video_url = base64.b64decode(video_url).decode('utf8')
  218. audio_url = base64.b64decode(audio_url).decode('utf8')
  219. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_2']['vwidth']
  220. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_2'][
  221. 'vheight']
  222. video_url_dict["video_url"] = video_url
  223. video_url_dict["audio_url"] = audio_url
  224. video_url_dict["video_width"] = video_width
  225. video_url_dict["video_height"] = video_height
  226. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_1' in \
  227. video_info['videoResource']['dash_120fps']['video_list']:
  228. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_1'][
  229. 'backup_url_1']
  230. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_1'][
  231. 'backup_url_1']
  232. if len(video_url) % 3 == 1:
  233. video_url += '=='
  234. elif len(video_url) % 3 == 2:
  235. video_url += '='
  236. elif len(audio_url) % 3 == 1:
  237. audio_url += '=='
  238. elif len(audio_url) % 3 == 2:
  239. audio_url += '='
  240. video_url = base64.b64decode(video_url).decode('utf8')
  241. audio_url = base64.b64decode(audio_url).decode('utf8')
  242. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_1']['vwidth']
  243. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_1'][
  244. 'vheight']
  245. video_url_dict["video_url"] = video_url
  246. video_url_dict["audio_url"] = audio_url
  247. video_url_dict["video_width"] = video_width
  248. video_url_dict["video_height"] = video_height
  249. elif 'dynamic_video' in video_info['videoResource']['dash_120fps'] \
  250. and 'dynamic_video_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  251. and 'dynamic_audio_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  252. and len(
  253. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list']) != 0 \
  254. and len(
  255. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list']) != 0:
  256. video_url = \
  257. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  258. 'backup_url_1']
  259. audio_url = \
  260. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list'][-1][
  261. 'backup_url_1']
  262. if len(video_url) % 3 == 1:
  263. video_url += '=='
  264. elif len(video_url) % 3 == 2:
  265. video_url += '='
  266. elif len(audio_url) % 3 == 1:
  267. audio_url += '=='
  268. elif len(audio_url) % 3 == 2:
  269. audio_url += '='
  270. video_url = base64.b64decode(video_url).decode('utf8')
  271. audio_url = base64.b64decode(audio_url).decode('utf8')
  272. video_width = \
  273. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  274. 'vwidth']
  275. video_height = \
  276. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  277. 'vheight']
  278. video_url_dict["video_url"] = video_url
  279. video_url_dict["audio_url"] = audio_url
  280. video_url_dict["video_width"] = video_width
  281. video_url_dict["video_height"] = video_height
  282. else:
  283. video_url_dict["video_url"] = ''
  284. video_url_dict["audio_url"] = ''
  285. video_url_dict["video_width"] = 0
  286. video_url_dict["video_height"] = 0
  287. elif 'dash' in video_info['videoResource']:
  288. if "video_list" in video_info['videoResource']['dash'] and 'video_4' in \
  289. video_info['videoResource']['dash']['video_list']:
  290. video_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  291. audio_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  292. if len(video_url) % 3 == 1:
  293. video_url += '=='
  294. elif len(video_url) % 3 == 2:
  295. video_url += '='
  296. elif len(audio_url) % 3 == 1:
  297. audio_url += '=='
  298. elif len(audio_url) % 3 == 2:
  299. audio_url += '='
  300. video_url = base64.b64decode(video_url).decode('utf8')
  301. audio_url = base64.b64decode(audio_url).decode('utf8')
  302. video_width = video_info['videoResource']['dash']['video_list']['video_4']['vwidth']
  303. video_height = video_info['videoResource']['dash']['video_list']['video_4']['vheight']
  304. video_url_dict["video_url"] = video_url
  305. video_url_dict["audio_url"] = audio_url
  306. video_url_dict["video_width"] = video_width
  307. video_url_dict["video_height"] = video_height
  308. elif "video_list" in video_info['videoResource']['dash'] and 'video_3' in \
  309. video_info['videoResource']['dash']['video_list']:
  310. video_url = video_info['videoResource']['dash']['video_list']['video_3']['backup_url_1']
  311. audio_url = video_info['videoResource']['dash']['video_list']['video_3']['backup_url_1']
  312. if len(video_url) % 3 == 1:
  313. video_url += '=='
  314. elif len(video_url) % 3 == 2:
  315. video_url += '='
  316. elif len(audio_url) % 3 == 1:
  317. audio_url += '=='
  318. elif len(audio_url) % 3 == 2:
  319. audio_url += '='
  320. video_url = base64.b64decode(video_url).decode('utf8')
  321. audio_url = base64.b64decode(audio_url).decode('utf8')
  322. video_width = video_info['videoResource']['dash']['video_list']['video_3']['vwidth']
  323. video_height = video_info['videoResource']['dash']['video_list']['video_3']['vheight']
  324. video_url_dict["video_url"] = video_url
  325. video_url_dict["audio_url"] = audio_url
  326. video_url_dict["video_width"] = video_width
  327. video_url_dict["video_height"] = video_height
  328. elif "video_list" in video_info['videoResource']['dash'] and 'video_2' in \
  329. video_info['videoResource']['dash']['video_list']:
  330. video_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  331. audio_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  332. if len(video_url) % 3 == 1:
  333. video_url += '=='
  334. elif len(video_url) % 3 == 2:
  335. video_url += '='
  336. elif len(audio_url) % 3 == 1:
  337. audio_url += '=='
  338. elif len(audio_url) % 3 == 2:
  339. audio_url += '='
  340. video_url = base64.b64decode(video_url).decode('utf8')
  341. audio_url = base64.b64decode(audio_url).decode('utf8')
  342. video_width = video_info['videoResource']['dash']['video_list']['video_2']['vwidth']
  343. video_height = video_info['videoResource']['dash']['video_list']['video_2']['vheight']
  344. video_url_dict["video_url"] = video_url
  345. video_url_dict["audio_url"] = audio_url
  346. video_url_dict["video_width"] = video_width
  347. video_url_dict["video_height"] = video_height
  348. elif "video_list" in video_info['videoResource']['dash'] and 'video_1' in \
  349. video_info['videoResource']['dash']['video_list']:
  350. video_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  351. audio_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  352. if len(video_url) % 3 == 1:
  353. video_url += '=='
  354. elif len(video_url) % 3 == 2:
  355. video_url += '='
  356. elif len(audio_url) % 3 == 1:
  357. audio_url += '=='
  358. elif len(audio_url) % 3 == 2:
  359. audio_url += '='
  360. video_url = base64.b64decode(video_url).decode('utf8')
  361. audio_url = base64.b64decode(audio_url).decode('utf8')
  362. video_width = video_info['videoResource']['dash']['video_list']['video_1']['vwidth']
  363. video_height = video_info['videoResource']['dash']['video_list']['video_1']['vheight']
  364. video_url_dict["video_url"] = video_url
  365. video_url_dict["audio_url"] = audio_url
  366. video_url_dict["video_width"] = video_width
  367. video_url_dict["video_height"] = video_height
  368. elif 'dynamic_video' in video_info['videoResource']['dash'] \
  369. and 'dynamic_video_list' in video_info['videoResource']['dash']['dynamic_video'] \
  370. and 'dynamic_audio_list' in video_info['videoResource']['dash']['dynamic_video'] \
  371. and len(video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list']) != 0 \
  372. and len(
  373. video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list']) != 0:
  374. video_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1][
  375. 'backup_url_1']
  376. audio_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list'][-1][
  377. 'backup_url_1']
  378. if len(video_url) % 3 == 1:
  379. video_url += '=='
  380. elif len(video_url) % 3 == 2:
  381. video_url += '='
  382. elif len(audio_url) % 3 == 1:
  383. audio_url += '=='
  384. elif len(audio_url) % 3 == 2:
  385. audio_url += '='
  386. video_url = base64.b64decode(video_url).decode('utf8')
  387. audio_url = base64.b64decode(audio_url).decode('utf8')
  388. video_width = \
  389. video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1]['vwidth']
  390. video_height = \
  391. video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1]['vheight']
  392. video_url_dict["video_url"] = video_url
  393. video_url_dict["audio_url"] = audio_url
  394. video_url_dict["video_width"] = video_width
  395. video_url_dict["video_height"] = video_height
  396. else:
  397. video_url_dict["video_url"] = ''
  398. video_url_dict["audio_url"] = ''
  399. video_url_dict["video_width"] = 0
  400. video_url_dict["video_height"] = 0
  401. elif 'normal' in video_info['videoResource']:
  402. if "video_list" in video_info['videoResource']['normal'] and 'video_4' in \
  403. video_info['videoResource']['normal']['video_list']:
  404. video_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  405. audio_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  406. if len(video_url) % 3 == 1:
  407. video_url += '=='
  408. elif len(video_url) % 3 == 2:
  409. video_url += '='
  410. elif len(audio_url) % 3 == 1:
  411. audio_url += '=='
  412. elif len(audio_url) % 3 == 2:
  413. audio_url += '='
  414. video_url = base64.b64decode(video_url).decode('utf8')
  415. audio_url = base64.b64decode(audio_url).decode('utf8')
  416. video_width = video_info['videoResource']['normal']['video_list']['video_4']['vwidth']
  417. video_height = video_info['videoResource']['normal']['video_list']['video_4']['vheight']
  418. video_url_dict["video_url"] = video_url
  419. video_url_dict["audio_url"] = audio_url
  420. video_url_dict["video_width"] = video_width
  421. video_url_dict["video_height"] = video_height
  422. elif "video_list" in video_info['videoResource']['normal'] and 'video_3' in \
  423. video_info['videoResource']['normal']['video_list']:
  424. video_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  425. audio_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  426. if len(video_url) % 3 == 1:
  427. video_url += '=='
  428. elif len(video_url) % 3 == 2:
  429. video_url += '='
  430. elif len(audio_url) % 3 == 1:
  431. audio_url += '=='
  432. elif len(audio_url) % 3 == 2:
  433. audio_url += '='
  434. video_url = base64.b64decode(video_url).decode('utf8')
  435. audio_url = base64.b64decode(audio_url).decode('utf8')
  436. video_width = video_info['videoResource']['normal']['video_list']['video_3']['vwidth']
  437. video_height = video_info['videoResource']['normal']['video_list']['video_3']['vheight']
  438. video_url_dict["video_url"] = video_url
  439. video_url_dict["audio_url"] = audio_url
  440. video_url_dict["video_width"] = video_width
  441. video_url_dict["video_height"] = video_height
  442. elif "video_list" in video_info['videoResource']['normal'] and 'video_2' in \
  443. video_info['videoResource']['normal']['video_list']:
  444. video_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  445. audio_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  446. if len(video_url) % 3 == 1:
  447. video_url += '=='
  448. elif len(video_url) % 3 == 2:
  449. video_url += '='
  450. elif len(audio_url) % 3 == 1:
  451. audio_url += '=='
  452. elif len(audio_url) % 3 == 2:
  453. audio_url += '='
  454. video_url = base64.b64decode(video_url).decode('utf8')
  455. audio_url = base64.b64decode(audio_url).decode('utf8')
  456. video_width = video_info['videoResource']['normal']['video_list']['video_2']['vwidth']
  457. video_height = video_info['videoResource']['normal']['video_list']['video_2']['vheight']
  458. video_url_dict["video_url"] = video_url
  459. video_url_dict["audio_url"] = audio_url
  460. video_url_dict["video_width"] = video_width
  461. video_url_dict["video_height"] = video_height
  462. elif "video_list" in video_info['videoResource']['normal'] and 'video_1' in \
  463. video_info['videoResource']['normal']['video_list']:
  464. video_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  465. audio_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  466. if len(video_url) % 3 == 1:
  467. video_url += '=='
  468. elif len(video_url) % 3 == 2:
  469. video_url += '='
  470. elif len(audio_url) % 3 == 1:
  471. audio_url += '=='
  472. elif len(audio_url) % 3 == 2:
  473. audio_url += '='
  474. video_url = base64.b64decode(video_url).decode('utf8')
  475. audio_url = base64.b64decode(audio_url).decode('utf8')
  476. video_width = video_info['videoResource']['normal']['video_list']['video_1']['vwidth']
  477. video_height = video_info['videoResource']['normal']['video_list']['video_1']['vheight']
  478. video_url_dict["video_url"] = video_url
  479. video_url_dict["audio_url"] = audio_url
  480. video_url_dict["video_width"] = video_width
  481. video_url_dict["video_height"] = video_height
  482. elif 'dynamic_video' in video_info['videoResource']['normal'] \
  483. and 'dynamic_video_list' in video_info['videoResource']['normal']['dynamic_video'] \
  484. and 'dynamic_audio_list' in video_info['videoResource']['normal']['dynamic_video'] \
  485. and len(
  486. video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list']) != 0 \
  487. and len(
  488. video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list']) != 0:
  489. video_url = \
  490. video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  491. 'backup_url_1']
  492. audio_url = \
  493. video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list'][-1][
  494. 'backup_url_1']
  495. if len(video_url) % 3 == 1:
  496. video_url += '=='
  497. elif len(video_url) % 3 == 2:
  498. video_url += '='
  499. elif len(audio_url) % 3 == 1:
  500. audio_url += '=='
  501. elif len(audio_url) % 3 == 2:
  502. audio_url += '='
  503. video_url = base64.b64decode(video_url).decode('utf8')
  504. audio_url = base64.b64decode(audio_url).decode('utf8')
  505. video_width = \
  506. video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  507. 'vwidth']
  508. video_height = \
  509. video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  510. 'vheight']
  511. video_url_dict["video_url"] = video_url
  512. video_url_dict["audio_url"] = audio_url
  513. video_url_dict["video_width"] = video_width
  514. video_url_dict["video_height"] = video_height
  515. else:
  516. video_url_dict["video_url"] = ''
  517. video_url_dict["audio_url"] = ''
  518. video_url_dict["video_width"] = 0
  519. video_url_dict["video_height"] = 0
  520. else:
  521. video_url_dict["video_url"] = ''
  522. video_url_dict["audio_url"] = ''
  523. video_url_dict["video_width"] = 0
  524. video_url_dict["video_height"] = 0
  525. return video_url_dict
  526. except Exception as e:
  527. Common.logger(log_type, crawler).error(f'get_video_url:{e}\n')
  528. # 过滤词库
  529. @classmethod
  530. def filter_words(cls, log_type, crawler):
  531. try:
  532. while True:
  533. filter_words_sheet = Feishu.get_values_batch(log_type, crawler, 'KGB4Hc')
  534. if filter_words_sheet is None:
  535. Common.logger(log_type, crawler).warning(
  536. f"filter_words_sheet:{filter_words_sheet} 10秒钟后重试")
  537. continue
  538. filter_words_list = []
  539. for x in filter_words_sheet:
  540. for y in x:
  541. if y is None:
  542. pass
  543. else:
  544. filter_words_list.append(y)
  545. return filter_words_list
  546. except Exception as e:
  547. Common.logger(log_type, crawler).error(f'filter_words异常:{e}\n')
  548. @classmethod
  549. def get_videolist(cls, log_type, crawler, env):
  550. while True:
  551. try:
  552. # signature = f"_{cls.random_signature()}"
  553. signature = cls.get_signature(env)
  554. if signature is None:
  555. Common.logger(log_type, crawler).warning(f"signature:{signature}")
  556. continue
  557. url = "https://www.ixigua.com/api/feedv2/feedById?"
  558. params = {
  559. "channelId": "94349543909",
  560. "count": "9",
  561. "maxTime": str(int(time.time())),
  562. "queryCount": "1",
  563. "_signature": signature,
  564. # "_signature": '_02B4Z6wo00001O38UmAAAIDBlTK5ZUm9hMDt7HbAAF9Se5',
  565. # "_signature": '_02B4Z6wo0000158YzJQAAIDC59YnkMoXHRufGMgAAIP97SpOQxVfKP5yN1rB9OQ2Be5sOOQWgCiFaeOyxlnCG4RZUX7NfDmED3tHWe2-vSJ-icJj7GZCBorr2AT2MY.Tm6TzjyGTXhKwp98X5f'
  566. # "maxTime": "1680867875",
  567. # "request_from": "701",
  568. # "offset": "0",
  569. # "referrer:": "https://open.weixin.qq.com/",
  570. # "aid": "1768",
  571. # "msToken": "Tqe-W_gibxblmWtCV1PoAUBjAb9W9lPoz8iX8OK9MS1XfRogNdVXeoxc69AKWSEObCuHssPmeRuJe1IH_G3nmTxrJc4XJMEs5iQ2ea36jFmKCTVkJ-9p-M7gcdQz3fw=",
  572. # "X-Bogus": "DFSzswVuZ6UAN9WvtV34uY/F6qyN",
  573. }
  574. headers = {
  575. 'referer': 'https://www.ixigua.com/?is_new_connect=0&is_new_user=0',
  576. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.54',
  577. # 'authority': 'www.ixigua.com',
  578. # 'accept': 'application/json, text/plain, */*',
  579. # 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  580. # 'cache-control': 'no-cache',
  581. # 'cookie': 'MONITOR_WEB_ID=67cb5099-a022-4ec3-bb8e-c4de6ba51dd0; s_v_web_id=verify_lef4i99x_32SosrdH_Qrtk_4LJn_8S7q_fhu16xe3s8ZV; support_webp=true; support_avif=false; csrf_session_id=a5355d954d3c63ed1ba35faada452b4d; passport_csrf_token=72b2574f3c99f8ba670e42df430218fd; passport_csrf_token_default=72b2574f3c99f8ba670e42df430218fd; sid_guard=c7472b508ea631823ba765a60cf8757f%7C1680867422%7C3024002%7CFri%2C+12-May-2023+11%3A37%3A04+GMT; uid_tt=c13f47d51767f616befe32fb3e9f485a; uid_tt_ss=c13f47d51767f616befe32fb3e9f485a; sid_tt=c7472b508ea631823ba765a60cf8757f; sessionid=c7472b508ea631823ba765a60cf8757f; sessionid_ss=c7472b508ea631823ba765a60cf8757f; sid_ucp_v1=1.0.0-KGUzNWYxNmRkZGJiZjgxY2MzZWNkMTEzMTkwYjY1Yjg5OTY5NzVlNmMKFQiu3d-eqQIQ3oDAoQYYGCAMOAhACxoCaGwiIGM3NDcyYjUwOGVhNjMxODIzYmE3NjVhNjBjZjg3NTdm; ssid_ucp_v1=1.0.0-KGUzNWYxNmRkZGJiZjgxY2MzZWNkMTEzMTkwYjY1Yjg5OTY5NzVlNmMKFQiu3d-eqQIQ3oDAoQYYGCAMOAhACxoCaGwiIGM3NDcyYjUwOGVhNjMxODIzYmE3NjVhNjBjZjg3NTdm; __ac_nonce=064300065001db7f6a17b; __ac_signature=_02B4Z6wo00f01818fmAAAIDCtbKVZ8QwbVPNXHrAAJd4Fp5IJBrYy-5AgEoa72Xn.rSoHeAReu30RHJAVrhA5vJusD5C-.mKhoov6Xgsg-ppp08LmOqE770Q-TRNhVGRJBKwb1ueF3QyPH2Jca; odin_tt=b893608d4dde2e1e8df8cd5d97a0e2fbeafc4ca762ac72ebef6e6c97e2ed19859bb01d46b4190ddd6dd17d7f9678e1de; msToken=Tqe-W_gibxblmWtCV1PoAUBjAb9W9lPoz8iX8OK9MS1XfRogNdVXeoxc69AKWSEObCuHssPmeRuJe1IH_G3nmTxrJc4XJMEs5iQ2ea36jFmKCTVkJ-9p-M7gcdQz3fw=; tt_scid=7SO17t4-YtgZpkEX-9CRvB9s98xYEiDf-C10y9i1SxUCRIQFbRgr8N8Hkb5JXjjZ83e7; ttwid=1%7CHHtv2QqpSGuSu8r-zXF1QoWsvjmNi1SJrqOrZzg-UCY%7C1680867977%7C9027097968bd917c32a425e8d5661663df403e6a57a38dff12d4725a783f247c; ixigua-a-s=1; ixigua-a-s=3',
  582. # 'pragma': 'no-cache',
  583. # 'sec-ch-ua': '"Microsoft Edge";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
  584. # 'sec-ch-ua-mobile': '?0',
  585. # 'sec-ch-ua-platform': '"macOS"',
  586. # 'sec-fetch-dest': 'empty',
  587. # 'sec-fetch-mode': 'cors',
  588. # 'sec-fetch-site': 'same-origin',
  589. # 'tt-anti-token': 'r8MhLGUgtoX-95d1758d7d3522be689af62ddc195c1ed6adb1249ca9cb84b39168213da98c63',
  590. # 'x-secsdk-csrf-token': '00010000000182d3d5c3e286e4c4538dd74a7ae03396eabdcc95b454f49a1e6029b52f9046fb1753a48082f54679'
  591. }
  592. urllib3.disable_warnings()
  593. s = requests.session()
  594. # max_retries=3 重试3次
  595. s.mount('http://', HTTPAdapter(max_retries=3))
  596. s.mount('https://', HTTPAdapter(max_retries=3))
  597. response = requests.get(url=url, headers=headers, params=params, proxies=Common.tunnel_proxies(), verify=False, timeout=5)
  598. response.close()
  599. if response.status_code != 200:
  600. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.text}\n")
  601. return
  602. elif 'data' not in response.text:
  603. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.text}\n")
  604. return
  605. elif 'channelFeed' not in response.json()['data']:
  606. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.json()}\n")
  607. return
  608. elif 'Data' not in response.json()['data']['channelFeed']:
  609. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.json()}\n")
  610. return
  611. elif len(response.json()['data']['channelFeed']['Data']) == 0:
  612. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.json()}\n")
  613. return
  614. else:
  615. videoList = response.json()['data']['channelFeed']['Data']
  616. for i in range(len(videoList)):
  617. if 'data' not in videoList[i]:
  618. continue
  619. # video_title
  620. video_title = videoList[i]['data'].get('title', '')
  621. # video_id
  622. video_id = videoList[i]['data'].get('vid', '')
  623. # play_cnt
  624. play_cnt = int(videoList[i]['data'].get('playNum', 0))
  625. # comment_cnt
  626. comment_cnt = int(videoList[i]['data'].get('commentNum', 0))
  627. # gid
  628. gid = videoList[i]['data'].get('item_id', 0)
  629. # share_cnt / like_cnt
  630. share_cnt = 0
  631. like_cnt = 0
  632. # duration
  633. duration = int(videoList[i]['data'].get('duration', 0))
  634. # publish_time_stamp
  635. publish_time_stamp = int(videoList[i]['data'].get('publish_time', 0))
  636. # publish_time_str
  637. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time_stamp))
  638. # cover_url
  639. cover_url = videoList[i]['data'].get('image_url', '')
  640. # user_name
  641. user_name = videoList[i]['data']['user_info'].get('name', '')
  642. # user_id
  643. user_id = videoList[i]['data']['user_info'].get('user_id', '')
  644. # avatar_url
  645. avatar_url = videoList[i]['data']['user_info'].get('avatar_url', '')
  646. if gid == 0 or video_id == '' or cover_url == '':
  647. Common.logger(log_type, crawler).info(f'{video_title}:无效视频\n')
  648. else:
  649. video_url_dict = cls.get_video_url(log_type, crawler, gid)
  650. video_url = video_url_dict["video_url"]
  651. audio_url = video_url_dict["audio_url"]
  652. video_width = video_url_dict["video_width"]
  653. video_height = video_url_dict["video_height"]
  654. video_dict = {
  655. 'video_title': video_title,
  656. 'video_id': video_id,
  657. 'gid': gid,
  658. 'play_cnt': play_cnt,
  659. 'comment_cnt': comment_cnt,
  660. 'like_cnt': like_cnt,
  661. 'share_cnt': share_cnt,
  662. 'video_width': video_width,
  663. 'video_height': video_height,
  664. 'duration': duration,
  665. 'publish_time_stamp': publish_time_stamp,
  666. 'publish_time_str': publish_time_str,
  667. 'user_name': user_name,
  668. 'user_id': user_id,
  669. 'avatar_url': avatar_url,
  670. 'cover_url': cover_url,
  671. 'audio_url': audio_url,
  672. 'video_url': video_url,
  673. 'session': signature
  674. }
  675. for k, v in video_dict.items():
  676. Common.logger(log_type, crawler).info(f"{k}:{v}")
  677. cls.download_publish(log_type, crawler, video_dict)
  678. except Exception as e:
  679. Common.logger(log_type, crawler).error(f"get_videolist:{e}\n")
  680. @classmethod
  681. def download_publish(cls, log_type, crawler, video_dict):
  682. if video_dict['video_id'] in [y for x in Feishu.get_values_batch(log_type, crawler, "1iKGF1") for y in x]:
  683. Common.logger(log_type, crawler).info("视频已存在\n")
  684. elif any(word if word in video_dict['video_title'] else False for word in
  685. cls.filter_words(log_type, crawler)) is True:
  686. Common.logger(log_type, crawler).info('标题已中过滤词\n')
  687. else:
  688. Feishu.insert_columns(log_type, crawler, "1iKGF1", "ROWS", 1, 2)
  689. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  690. "西瓜推荐榜",
  691. video_dict['video_title'],
  692. video_dict['video_id'],
  693. "",
  694. video_dict['gid'],
  695. video_dict['play_cnt'],
  696. video_dict['comment_cnt'],
  697. video_dict['like_cnt'],
  698. video_dict['share_cnt'],
  699. video_dict['duration'],
  700. f"{video_dict['video_width']}*{video_dict['video_height']}",
  701. video_dict['publish_time_str'],
  702. video_dict['user_name'],
  703. video_dict['user_id'],
  704. video_dict['avatar_url'],
  705. video_dict['cover_url'],
  706. video_dict['audio_url'],
  707. video_dict['video_url']]]
  708. time.sleep(0.5)
  709. Feishu.update_values(log_type, crawler, "1iKGF1", "F2:Z2", values)
  710. Common.logger(log_type, crawler).info("写入飞书成功\n")
  711. if __name__ == "__main__":
  712. # XiguaRecommend.get_signature("recommend", "xigua", "dev")
  713. XiguaRecommend.get_videolist("recommend", "xigua", "dev")
  714. # print(XiguaRecommend.get_video_url("recommend", "xigua", "7218171653242094139"))
  715. # print(XiguaRecommend.filter_words("recommend", "xigua"))
  716. pass