xigua_search_scheduling.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/5/26
  4. import base64
  5. import json
  6. import os
  7. import random
  8. import shutil
  9. import string
  10. import sys
  11. import time
  12. from hashlib import md5
  13. import requests
  14. import urllib3
  15. from requests.adapters import HTTPAdapter
  16. from selenium.webdriver import DesiredCapabilities
  17. from selenium.webdriver.chrome.service import Service
  18. from selenium import webdriver
  19. from selenium.webdriver.common.by import By
  20. sys.path.append(os.getcwd())
  21. from common.scheduling_db import MysqlHelper
  22. from common.common import Common
  23. from common.feishu import Feishu
  24. from common.publish import Publish
  25. from common.public import get_config_from_mysql, download_rule
  26. from common.userAgent import get_random_user_agent
  27. class XiguasearchScheduling:
  28. # 已下载视频数
  29. download_cnt = 0
  30. platform = "西瓜视频"
  31. @classmethod
  32. def random_signature(cls):
  33. src_digits = string.digits # string_数字
  34. src_uppercase = string.ascii_uppercase # string_大写字母
  35. src_lowercase = string.ascii_lowercase # string_小写字母
  36. digits_num = random.randint(1, 6)
  37. uppercase_num = random.randint(1, 26 - digits_num - 1)
  38. lowercase_num = 26 - (digits_num + uppercase_num)
  39. password = random.sample(src_digits, digits_num) + random.sample(src_uppercase, uppercase_num) + random.sample(
  40. src_lowercase, lowercase_num)
  41. random.shuffle(password)
  42. new_password = 'AAAAAAAAAA' + ''.join(password)[10:-4] + 'AAAB'
  43. new_password_start = new_password[0:18]
  44. new_password_end = new_password[-7:]
  45. if new_password[18] == '8':
  46. new_password = new_password_start + 'w' + new_password_end
  47. elif new_password[18] == '9':
  48. new_password = new_password_start + 'x' + new_password_end
  49. elif new_password[18] == '-':
  50. new_password = new_password_start + 'y' + new_password_end
  51. elif new_password[18] == '.':
  52. new_password = new_password_start + 'z' + new_password_end
  53. else:
  54. new_password = new_password_start + 'y' + new_password_end
  55. return new_password
  56. @classmethod
  57. def get_video_url(cls, video_info):
  58. video_url_dict = {}
  59. # video_url
  60. if 'videoResource' not in video_info:
  61. video_url_dict["video_url"] = ''
  62. video_url_dict["audio_url"] = ''
  63. video_url_dict["video_width"] = 0
  64. video_url_dict["video_height"] = 0
  65. elif 'dash_120fps' in video_info['videoResource']:
  66. if "video_list" in video_info['videoResource']['dash_120fps'] and 'video_4' in \
  67. video_info['videoResource']['dash_120fps']['video_list']:
  68. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_4']['backup_url_1']
  69. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_4']['backup_url_1']
  70. if len(video_url) % 3 == 1:
  71. video_url += '=='
  72. elif len(video_url) % 3 == 2:
  73. video_url += '='
  74. elif len(audio_url) % 3 == 1:
  75. audio_url += '=='
  76. elif len(audio_url) % 3 == 2:
  77. audio_url += '='
  78. video_url = base64.b64decode(video_url).decode('utf8')
  79. audio_url = base64.b64decode(audio_url).decode('utf8')
  80. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_4']['vwidth']
  81. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_4']['vheight']
  82. video_url_dict["video_url"] = video_url
  83. video_url_dict["audio_url"] = audio_url
  84. video_url_dict["video_width"] = video_width
  85. video_url_dict["video_height"] = video_height
  86. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_3' in \
  87. video_info['videoResource']['dash_120fps']['video_list']:
  88. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_3']['backup_url_1']
  89. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_3']['backup_url_1']
  90. if len(video_url) % 3 == 1:
  91. video_url += '=='
  92. elif len(video_url) % 3 == 2:
  93. video_url += '='
  94. elif len(audio_url) % 3 == 1:
  95. audio_url += '=='
  96. elif len(audio_url) % 3 == 2:
  97. audio_url += '='
  98. video_url = base64.b64decode(video_url).decode('utf8')
  99. audio_url = base64.b64decode(audio_url).decode('utf8')
  100. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_3']['vwidth']
  101. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_3']['vheight']
  102. video_url_dict["video_url"] = video_url
  103. video_url_dict["audio_url"] = audio_url
  104. video_url_dict["video_width"] = video_width
  105. video_url_dict["video_height"] = video_height
  106. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_2' in \
  107. video_info['videoResource']['dash_120fps']['video_list']:
  108. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_2']['backup_url_1']
  109. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_2']['backup_url_1']
  110. if len(video_url) % 3 == 1:
  111. video_url += '=='
  112. elif len(video_url) % 3 == 2:
  113. video_url += '='
  114. elif len(audio_url) % 3 == 1:
  115. audio_url += '=='
  116. elif len(audio_url) % 3 == 2:
  117. audio_url += '='
  118. video_url = base64.b64decode(video_url).decode('utf8')
  119. audio_url = base64.b64decode(audio_url).decode('utf8')
  120. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_2']['vwidth']
  121. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_2']['vheight']
  122. video_url_dict["video_url"] = video_url
  123. video_url_dict["audio_url"] = audio_url
  124. video_url_dict["video_width"] = video_width
  125. video_url_dict["video_height"] = video_height
  126. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_1' in \
  127. video_info['videoResource']['dash_120fps']['video_list']:
  128. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_1']['backup_url_1']
  129. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_1']['backup_url_1']
  130. if len(video_url) % 3 == 1:
  131. video_url += '=='
  132. elif len(video_url) % 3 == 2:
  133. video_url += '='
  134. elif len(audio_url) % 3 == 1:
  135. audio_url += '=='
  136. elif len(audio_url) % 3 == 2:
  137. audio_url += '='
  138. video_url = base64.b64decode(video_url).decode('utf8')
  139. audio_url = base64.b64decode(audio_url).decode('utf8')
  140. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_1']['vwidth']
  141. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_1']['vheight']
  142. video_url_dict["video_url"] = video_url
  143. video_url_dict["audio_url"] = audio_url
  144. video_url_dict["video_width"] = video_width
  145. video_url_dict["video_height"] = video_height
  146. elif 'dynamic_video' in video_info['videoResource']['dash_120fps'] \
  147. and 'dynamic_video_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  148. and 'dynamic_audio_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  149. and len(
  150. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list']) != 0 \
  151. and len(
  152. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list']) != 0:
  153. video_url = \
  154. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  155. 'backup_url_1']
  156. audio_url = \
  157. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list'][-1][
  158. 'backup_url_1']
  159. if len(video_url) % 3 == 1:
  160. video_url += '=='
  161. elif len(video_url) % 3 == 2:
  162. video_url += '='
  163. elif len(audio_url) % 3 == 1:
  164. audio_url += '=='
  165. elif len(audio_url) % 3 == 2:
  166. audio_url += '='
  167. video_url = base64.b64decode(video_url).decode('utf8')
  168. audio_url = base64.b64decode(audio_url).decode('utf8')
  169. video_width = \
  170. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  171. 'vwidth']
  172. video_height = \
  173. video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1][
  174. 'vheight']
  175. video_url_dict["video_url"] = video_url
  176. video_url_dict["audio_url"] = audio_url
  177. video_url_dict["video_width"] = video_width
  178. video_url_dict["video_height"] = video_height
  179. else:
  180. video_url_dict["video_url"] = ''
  181. video_url_dict["audio_url"] = ''
  182. video_url_dict["video_width"] = 0
  183. video_url_dict["video_height"] = 0
  184. elif 'dash' in video_info['videoResource']:
  185. if "video_list" in video_info['videoResource']['dash'] and 'video_4' in \
  186. video_info['videoResource']['dash']['video_list']:
  187. video_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  188. audio_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  189. if len(video_url) % 3 == 1:
  190. video_url += '=='
  191. elif len(video_url) % 3 == 2:
  192. video_url += '='
  193. elif len(audio_url) % 3 == 1:
  194. audio_url += '=='
  195. elif len(audio_url) % 3 == 2:
  196. audio_url += '='
  197. video_url = base64.b64decode(video_url).decode('utf8')
  198. audio_url = base64.b64decode(audio_url).decode('utf8')
  199. video_width = video_info['videoResource']['dash']['video_list']['video_4']['vwidth']
  200. video_height = video_info['videoResource']['dash']['video_list']['video_4']['vheight']
  201. video_url_dict["video_url"] = video_url
  202. video_url_dict["audio_url"] = audio_url
  203. video_url_dict["video_width"] = video_width
  204. video_url_dict["video_height"] = video_height
  205. elif "video_list" in video_info['videoResource']['dash'] and 'video_3' in \
  206. video_info['videoResource']['dash']['video_list']:
  207. video_url = video_info['videoResource']['dash']['video_list']['video_3']['backup_url_1']
  208. audio_url = video_info['videoResource']['dash']['video_list']['video_3']['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']['video_list']['video_3']['vwidth']
  220. video_height = video_info['videoResource']['dash']['video_list']['video_3']['vheight']
  221. video_url_dict["video_url"] = video_url
  222. video_url_dict["audio_url"] = audio_url
  223. video_url_dict["video_width"] = video_width
  224. video_url_dict["video_height"] = video_height
  225. elif "video_list" in video_info['videoResource']['dash'] and 'video_2' in \
  226. video_info['videoResource']['dash']['video_list']:
  227. video_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  228. audio_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  229. if len(video_url) % 3 == 1:
  230. video_url += '=='
  231. elif len(video_url) % 3 == 2:
  232. video_url += '='
  233. elif len(audio_url) % 3 == 1:
  234. audio_url += '=='
  235. elif len(audio_url) % 3 == 2:
  236. audio_url += '='
  237. video_url = base64.b64decode(video_url).decode('utf8')
  238. audio_url = base64.b64decode(audio_url).decode('utf8')
  239. video_width = video_info['videoResource']['dash']['video_list']['video_2']['vwidth']
  240. video_height = video_info['videoResource']['dash']['video_list']['video_2']['vheight']
  241. video_url_dict["video_url"] = video_url
  242. video_url_dict["audio_url"] = audio_url
  243. video_url_dict["video_width"] = video_width
  244. video_url_dict["video_height"] = video_height
  245. elif "video_list" in video_info['videoResource']['dash'] and 'video_1' in \
  246. video_info['videoResource']['dash']['video_list']:
  247. video_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  248. audio_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  249. if len(video_url) % 3 == 1:
  250. video_url += '=='
  251. elif len(video_url) % 3 == 2:
  252. video_url += '='
  253. elif len(audio_url) % 3 == 1:
  254. audio_url += '=='
  255. elif len(audio_url) % 3 == 2:
  256. audio_url += '='
  257. video_url = base64.b64decode(video_url).decode('utf8')
  258. audio_url = base64.b64decode(audio_url).decode('utf8')
  259. video_width = video_info['videoResource']['dash']['video_list']['video_1']['vwidth']
  260. video_height = video_info['videoResource']['dash']['video_list']['video_1']['vheight']
  261. video_url_dict["video_url"] = video_url
  262. video_url_dict["audio_url"] = audio_url
  263. video_url_dict["video_width"] = video_width
  264. video_url_dict["video_height"] = video_height
  265. elif 'dynamic_video' in video_info['videoResource']['dash'] \
  266. and 'dynamic_video_list' in video_info['videoResource']['dash']['dynamic_video'] \
  267. and 'dynamic_audio_list' in video_info['videoResource']['dash']['dynamic_video'] \
  268. and len(video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list']) != 0 \
  269. and len(video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list']) != 0:
  270. video_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1][
  271. 'backup_url_1']
  272. audio_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list'][-1][
  273. 'backup_url_1']
  274. if len(video_url) % 3 == 1:
  275. video_url += '=='
  276. elif len(video_url) % 3 == 2:
  277. video_url += '='
  278. elif len(audio_url) % 3 == 1:
  279. audio_url += '=='
  280. elif len(audio_url) % 3 == 2:
  281. audio_url += '='
  282. video_url = base64.b64decode(video_url).decode('utf8')
  283. audio_url = base64.b64decode(audio_url).decode('utf8')
  284. video_width = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1][
  285. 'vwidth']
  286. video_height = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1][
  287. 'vheight']
  288. video_url_dict["video_url"] = video_url
  289. video_url_dict["audio_url"] = audio_url
  290. video_url_dict["video_width"] = video_width
  291. video_url_dict["video_height"] = video_height
  292. else:
  293. video_url_dict["video_url"] = ''
  294. video_url_dict["audio_url"] = ''
  295. video_url_dict["video_width"] = 0
  296. video_url_dict["video_height"] = 0
  297. elif 'normal' in video_info['videoResource']:
  298. if "video_list" in video_info['videoResource']['normal'] and 'video_4' in \
  299. video_info['videoResource']['normal']['video_list']:
  300. video_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  301. audio_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  302. if len(video_url) % 3 == 1:
  303. video_url += '=='
  304. elif len(video_url) % 3 == 2:
  305. video_url += '='
  306. elif len(audio_url) % 3 == 1:
  307. audio_url += '=='
  308. elif len(audio_url) % 3 == 2:
  309. audio_url += '='
  310. video_url = base64.b64decode(video_url).decode('utf8')
  311. audio_url = base64.b64decode(audio_url).decode('utf8')
  312. video_width = video_info['videoResource']['normal']['video_list']['video_4']['vwidth']
  313. video_height = video_info['videoResource']['normal']['video_list']['video_4']['vheight']
  314. video_url_dict["video_url"] = video_url
  315. video_url_dict["audio_url"] = audio_url
  316. video_url_dict["video_width"] = video_width
  317. video_url_dict["video_height"] = video_height
  318. elif "video_list" in video_info['videoResource']['normal'] and 'video_3' in \
  319. video_info['videoResource']['normal']['video_list']:
  320. video_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  321. audio_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  322. if len(video_url) % 3 == 1:
  323. video_url += '=='
  324. elif len(video_url) % 3 == 2:
  325. video_url += '='
  326. elif len(audio_url) % 3 == 1:
  327. audio_url += '=='
  328. elif len(audio_url) % 3 == 2:
  329. audio_url += '='
  330. video_url = base64.b64decode(video_url).decode('utf8')
  331. audio_url = base64.b64decode(audio_url).decode('utf8')
  332. video_width = video_info['videoResource']['normal']['video_list']['video_3']['vwidth']
  333. video_height = video_info['videoResource']['normal']['video_list']['video_3']['vheight']
  334. video_url_dict["video_url"] = video_url
  335. video_url_dict["audio_url"] = audio_url
  336. video_url_dict["video_width"] = video_width
  337. video_url_dict["video_height"] = video_height
  338. elif "video_list" in video_info['videoResource']['normal'] and 'video_2' in \
  339. video_info['videoResource']['normal']['video_list']:
  340. video_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  341. audio_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  342. if len(video_url) % 3 == 1:
  343. video_url += '=='
  344. elif len(video_url) % 3 == 2:
  345. video_url += '='
  346. elif len(audio_url) % 3 == 1:
  347. audio_url += '=='
  348. elif len(audio_url) % 3 == 2:
  349. audio_url += '='
  350. video_url = base64.b64decode(video_url).decode('utf8')
  351. audio_url = base64.b64decode(audio_url).decode('utf8')
  352. video_width = video_info['videoResource']['normal']['video_list']['video_2']['vwidth']
  353. video_height = video_info['videoResource']['normal']['video_list']['video_2']['vheight']
  354. video_url_dict["video_url"] = video_url
  355. video_url_dict["audio_url"] = audio_url
  356. video_url_dict["video_width"] = video_width
  357. video_url_dict["video_height"] = video_height
  358. elif "video_list" in video_info['videoResource']['normal'] and 'video_1' in \
  359. video_info['videoResource']['normal']['video_list']:
  360. video_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  361. audio_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  362. if len(video_url) % 3 == 1:
  363. video_url += '=='
  364. elif len(video_url) % 3 == 2:
  365. video_url += '='
  366. elif len(audio_url) % 3 == 1:
  367. audio_url += '=='
  368. elif len(audio_url) % 3 == 2:
  369. audio_url += '='
  370. video_url = base64.b64decode(video_url).decode('utf8')
  371. audio_url = base64.b64decode(audio_url).decode('utf8')
  372. video_width = video_info['videoResource']['normal']['video_list']['video_1']['vwidth']
  373. video_height = video_info['videoResource']['normal']['video_list']['video_1']['vheight']
  374. video_url_dict["video_url"] = video_url
  375. video_url_dict["audio_url"] = audio_url
  376. video_url_dict["video_width"] = video_width
  377. video_url_dict["video_height"] = video_height
  378. elif 'dynamic_video' in video_info['videoResource']['normal'] \
  379. and 'dynamic_video_list' in video_info['videoResource']['normal']['dynamic_video'] \
  380. and 'dynamic_audio_list' in video_info['videoResource']['normal']['dynamic_video'] \
  381. and len(video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list']) != 0 \
  382. and len(video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list']) != 0:
  383. video_url = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  384. 'backup_url_1']
  385. audio_url = video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list'][-1][
  386. 'backup_url_1']
  387. if len(video_url) % 3 == 1:
  388. video_url += '=='
  389. elif len(video_url) % 3 == 2:
  390. video_url += '='
  391. elif len(audio_url) % 3 == 1:
  392. audio_url += '=='
  393. elif len(audio_url) % 3 == 2:
  394. audio_url += '='
  395. video_url = base64.b64decode(video_url).decode('utf8')
  396. audio_url = base64.b64decode(audio_url).decode('utf8')
  397. video_width = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  398. 'vwidth']
  399. video_height = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  400. 'vheight']
  401. video_url_dict["video_url"] = video_url
  402. video_url_dict["audio_url"] = audio_url
  403. video_url_dict["video_width"] = video_width
  404. video_url_dict["video_height"] = video_height
  405. else:
  406. video_url_dict["video_url"] = ''
  407. video_url_dict["audio_url"] = ''
  408. video_url_dict["video_width"] = 0
  409. video_url_dict["video_height"] = 0
  410. else:
  411. video_url_dict["video_url"] = ''
  412. video_url_dict["audio_url"] = ''
  413. video_url_dict["video_width"] = 0
  414. video_url_dict["video_height"] = 0
  415. return video_url_dict
  416. @classmethod
  417. def get_comment_cnt(cls, item_id):
  418. url = "https://www.ixigua.com/tlb/comment/article/v5/tab_comments/?"
  419. params = {
  420. "tab_index": "0",
  421. "count": "10",
  422. "offset": "10",
  423. "group_id": str(item_id),
  424. "item_id": str(item_id),
  425. "aid": "1768",
  426. "msToken": "50-JJObWB07HfHs-BMJWT1eIDX3G-6lPSF_i-QwxBIXE9VVa-iN0jbEXR5pG2DKjXBmP299n6ZTuXzY-GAy968CCvouSAYIS4GzvGQT3pNlKNejr5G4-1g==",
  427. "X-Bogus": "DFSzswVOyGtANVeWtCLMqR/F6q9U",
  428. "_signature": cls.random_signature(),
  429. }
  430. headers = {
  431. 'authority': 'www.ixigua.com',
  432. 'accept': 'application/json, text/plain, */*',
  433. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  434. 'cache-control': 'no-cache',
  435. 'cookie': 'MONITOR_WEB_ID=67cb5099-a022-4ec3-bb8e-c4de6ba51dd0; 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; odin_tt=b893608d4dde2e1e8df8cd5d97a0e2fbeafc4ca762ac72ebef6e6c97e2ed19859bb01d46b4190ddd6dd17d7f9678e1de; SEARCH_CARD_MODE=7168304743566296612_0; support_webp=true; support_avif=false; csrf_session_id=a5355d954d3c63ed1ba35faada452b4d; tt_scid=7Pux7s634-z8DYvCM20y7KigwH5u7Rh6D9C-RROpnT.aGMEcz6Vsxp.oai47wJqa4f86; ttwid=1%7CHHtv2QqpSGuSu8r-zXF1QoWsvjmNi1SJrqOrZzg-UCY%7C1683858689%7Ca5223fe1500578e01e138a0d71d6444692018296c4c24f5885af174a65873c95; ixigua-a-s=3; msToken=50-JJObWB07HfHs-BMJWT1eIDX3G-6lPSF_i-QwxBIXE9VVa-iN0jbEXR5pG2DKjXBmP299n6ZTuXzY-GAy968CCvouSAYIS4GzvGQT3pNlKNejr5G4-1g==; __ac_nonce=0645dcbf0005064517440; __ac_signature=_02B4Z6wo00f01FEGmAwAAIDBKchzCGqn-MBRJpyAAHAjieFC5GEg6gGiwz.I4PRrJl7f0GcixFrExKmgt6QI1i1S-dQyofPEj2ugWTCnmKUdJQv-wYuDofeKNe8VtMtZq2aKewyUGeKU-5Ud21; ixigua-a-s=3',
  436. 'pragma': 'no-cache',
  437. 'referer': f'https://www.ixigua.com/{item_id}?logTag=3c5aa86a8600b9ab8540',
  438. 'sec-ch-ua': '"Microsoft Edge";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
  439. 'sec-ch-ua-mobile': '?0',
  440. 'sec-ch-ua-platform': '"macOS"',
  441. 'sec-fetch-dest': 'empty',
  442. 'sec-fetch-mode': 'cors',
  443. 'sec-fetch-site': 'same-origin',
  444. 'tt-anti-token': 'cBITBHvmYjEygzv-f9c78c1297722cf1f559c74b084e4525ce4900bdcf9e8588f20cc7c2e3234422',
  445. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36 Edg/113.0.1774.35',
  446. 'x-secsdk-csrf-token': '000100000001f8e733cf37f0cd255a51aea9a81ff7bc0c09490cfe41ad827c3c5c18ec809279175e4d9f5553d8a5'
  447. }
  448. urllib3.disable_warnings()
  449. s = requests.session()
  450. # max_retries=3 重试3次
  451. s.mount('http://', HTTPAdapter(max_retries=3))
  452. s.mount('https://', HTTPAdapter(max_retries=3))
  453. response = s.get(url=url, headers=headers, params=params, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
  454. response.close()
  455. if response.status_code != 200 or 'total_number' not in response.json() or response.json() == {}:
  456. return 0
  457. return response.json().get("total_number", 0)
  458. # 获取视频详情
  459. @classmethod
  460. def get_video_info(cls, log_type, crawler, item_id):
  461. url = 'https://www.ixigua.com/api/mixVideo/information?'
  462. headers = {
  463. "accept-encoding": "gzip, deflate",
  464. "accept-language": "zh-CN,zh-Hans;q=0.9",
  465. "user-agent": get_random_user_agent('pc'),
  466. "referer": "https://www.ixigua.com/7102614741050196520?logTag=0531c88ac04f38ab2c62",
  467. }
  468. params = {
  469. 'mixId': str(item_id),
  470. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfC'
  471. 'NVVIOBNjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  472. 'X-Bogus': 'DFSzswVupYTANCJOSBk0P53WxM-r',
  473. '_signature': '_02B4Z6wo0000119LvEwAAIDCuktNZ0y5wkdfS7jAALThuOR8D9yWNZ.EmWHKV0WSn6Px'
  474. 'fPsH9-BldyxVje0f49ryXgmn7Tzk-swEHNb15TiGqa6YF.cX0jW8Eds1TtJOIZyfc9s5emH7gdWN94',
  475. }
  476. cookies = {
  477. 'ixigua-a-s': '1',
  478. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfCNVVIOB'
  479. 'NjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  480. 'ttwid': '1%7C_yXQeHWwLZgCsgHClOwTCdYSOt_MjdOkgnPIkpi-Sr8%7C1661241238%7Cf57d0c5ef3f1d7'
  481. '6e049fccdca1ac54887c34d1f8731c8e51a49780ff0ceab9f8',
  482. 'tt_scid': 'QZ4l8KXDG0YAEaMCSbADdcybdKbUfG4BC6S4OBv9lpRS5VyqYLX2bIR8CTeZeGHR9ee3',
  483. 'MONITOR_WEB_ID': '0a49204a-7af5-4e96-95f0-f4bafb7450ad',
  484. '__ac_nonce': '06304878000964fdad287',
  485. '__ac_signature': '_02B4Z6wo00f017Rcr3AAAIDCUVxeW1tOKEu0fKvAAI4cvoYzV-wBhq7B6D8k0no7lb'
  486. 'FlvYoinmtK6UXjRIYPXnahUlFTvmWVtb77jsMkKAXzAEsLE56m36RlvL7ky.M3Xn52r9t1IEb7IR3ke8',
  487. 'ttcid': 'e56fabf6e85d4adf9e4d91902496a0e882',
  488. '_tea_utm_cache_1300': 'undefined',
  489. 'support_avif': 'false',
  490. 'support_webp': 'false',
  491. 'xiguavideopcwebid': '7134967546256016900',
  492. 'xiguavideopcwebid.sig': 'xxRww5R1VEMJN_dQepHorEu_eAc',
  493. }
  494. urllib3.disable_warnings()
  495. s = requests.session()
  496. # max_retries=3 重试3次
  497. s.mount('http://', HTTPAdapter(max_retries=3))
  498. s.mount('https://', HTTPAdapter(max_retries=3))
  499. response = s.get(url=url, headers=headers, params=params, cookies=cookies, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
  500. response.close()
  501. if response.status_code != 200 or 'data' not in response.json() or response.json()['data'] == {}:
  502. Common.logger(log_type, crawler).warning(f"get_video_info:{response.status_code}, {response.text}\n")
  503. return None
  504. else:
  505. video_info = response.json()['data'].get("gidInformation", {}).get("packerData", {}).get("video", {})
  506. if video_info == {}:
  507. return None
  508. video_dict = {
  509. "video_title": video_info.get("title", ""),
  510. "video_id": video_info.get("videoResource", {}).get("vid", ""),
  511. "gid": str(item_id),
  512. "play_cnt": int(video_info.get("video_watch_count", 0)),
  513. "like_cnt": int(video_info.get("video_like_count", 0)),
  514. "comment_cnt": int(cls.get_comment_cnt(item_id)),
  515. "share_cnt": 0,
  516. "favorite_cnt": 0,
  517. "duration": int(video_info.get("video_duration", 0)),
  518. "video_width": int(cls.get_video_url(video_info)["video_width"]),
  519. "video_height": int(cls.get_video_url(video_info)["video_height"]),
  520. "publish_time_stamp": int(video_info.get("video_publish_time", 0)),
  521. "publish_time_str": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(video_info.get("video_publish_time", 0)))),
  522. "user_name": video_info.get("user_info", {}).get("name", ""),
  523. "user_id": str(video_info.get("user_info", {}).get("user_id", "")),
  524. "avatar_url": str(video_info.get("user_info", {}).get("avatar_url", "")),
  525. "cover_url": video_info.get("poster_url", ""),
  526. "audio_url": cls.get_video_url(video_info)["audio_url"],
  527. "video_url": cls.get_video_url(video_info)["video_url"],
  528. "session": f"xigua-search-{int(time.time())}"
  529. }
  530. return video_dict
  531. @classmethod
  532. def get_videoList(cls, log_type, crawler, user_dict, rule_dict, env):
  533. # 打印请求配置
  534. ca = DesiredCapabilities.CHROME
  535. ca["goog:loggingPrefs"] = {"performance": "ALL"}
  536. # # 不打开浏览器运行
  537. chrome_options = webdriver.ChromeOptions()
  538. chrome_options.add_argument(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')
  539. chrome_options.add_argument("--headless")
  540. chrome_options.add_argument("--window-size=1920,1080")
  541. chrome_options.add_argument("--no-sandbox")
  542. if env == "dev":
  543. chromedriver = "/Users/wangkun/Downloads/chromedriver/chromedriver_v112/chromedriver"
  544. else:
  545. chromedriver = "/usr/bin/chromedriver"
  546. # driver初始化
  547. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service(chromedriver))
  548. driver.implicitly_wait(10)
  549. Common.logger(log_type, crawler).info(f"打开搜索页:{user_dict['nick_name']}")
  550. driver.get(f"https://www.ixigua.com/search/{user_dict['nick_name']}/")
  551. time.sleep(3)
  552. # driver.get_screenshot_as_file(f"./{crawler}/logs/打开搜索页.jpg")
  553. if len(driver.find_elements(By.XPATH, '//*[@class="xg-notification-close"]')) != 0:
  554. driver.find_element(By.XPATH, '//*[@class="xg-notification-close"]').click()
  555. time.sleep(1)
  556. Common.logger(log_type, crawler).info("点击筛选")
  557. driver.find_element(By.XPATH, '//*[@class="searchPageV2__header-icons-categories"]').click()
  558. time.sleep(1)
  559. Common.logger(log_type, crawler).info("点击最新排序")
  560. driver.find_element(By.XPATH, '//*[@class="searchPageV2-category__wrapper"]/*[2]/*[1]').click()
  561. time.sleep(5)
  562. # driver.get_screenshot_as_file(f"./{crawler}/logs/已点击最新排序.jpg")
  563. index = 0
  564. num = 0
  565. while True:
  566. video_elements = driver.find_elements(By.XPATH, '//*[@class="HorizontalFeedCard searchPageV2__card"]')
  567. video_element_temp = video_elements[index:]
  568. if len(video_element_temp) == 0:
  569. Common.logger(log_type, crawler).info('到底啦~~~~~~~~~~~~~\n')
  570. driver.quit()
  571. return
  572. for i, video_element in enumerate(video_element_temp):
  573. try:
  574. if cls.download_cnt >= int(rule_dict.get("videos_cnt", {}).get("min", 30)):
  575. Common.logger(log_type, crawler).info(f"搜索词: {user_dict['nick_name']},已下载视频数: {cls.download_cnt}\n")
  576. driver.quit()
  577. return
  578. if video_element is None:
  579. Common.logger(log_type, crawler).info('到底啦~\n')
  580. driver.quit()
  581. return
  582. num += 1
  583. Common.logger(log_type, crawler).info(f'拖动"视频"列表第{num}个至屏幕中间')
  584. driver.execute_script("arguments[0].scrollIntoView({block:'center',inline:'center'})", video_element)
  585. time.sleep(1)
  586. item_id = video_element.find_elements(By.XPATH, '//*[@class="HorizontalFeedCard__coverWrapper disableZoomAnimation"]')[index+i].get_attribute('href')
  587. item_id = item_id.split("com/")[-1].split("?&")[0]
  588. video_dict = cls.get_video_info(log_type, crawler, item_id)
  589. if video_dict is None:
  590. Common.logger(log_type, crawler).info("无效视频\n")
  591. continue
  592. for k, v in video_dict.items():
  593. Common.logger(log_type, crawler).info(f"{k}:{v}")
  594. if int((int(time.time()) - int(video_dict["publish_time_stamp"])) / (3600 * 24)) > int(rule_dict.get("period", {}).get("max", 1000)):
  595. Common.logger(log_type, crawler).info(f'发布时间超过{int(rule_dict.get("period", {}).get("max", 1000))}天\n')
  596. driver.quit()
  597. return
  598. if download_rule(log_type=log_type, crawler=crawler, video_dict=video_dict, rule_dict=rule_dict) is False:
  599. Common.logger(log_type, crawler).info("不满足抓取规则\n")
  600. elif any(str(word) if str(word) in video_dict["video_title"] else False
  601. for word in get_config_from_mysql(log_type=log_type,
  602. source=crawler,
  603. env=env,
  604. text="filter",
  605. action="")) is True:
  606. Common.logger(log_type, crawler).info('已中过滤词\n')
  607. elif cls.repeat_video(log_type, crawler, video_dict["video_id"], env) != 0:
  608. Common.logger(log_type, crawler).info('视频已下载\n')
  609. else:
  610. cls.download_publish(log_type=log_type,
  611. crawler=crawler,
  612. user_dict=user_dict,
  613. video_dict=video_dict,
  614. rule_dict=rule_dict,
  615. env=env)
  616. except Exception as e:
  617. Common.logger(log_type, crawler).warning(f"抓取单条视频异常:{e}\n")
  618. Common.logger(log_type, crawler).info('已抓取完一组视频,休眠10秒\n')
  619. time.sleep(10)
  620. index = index + len(video_element_temp)
  621. @classmethod
  622. def repeat_video(cls, log_type, crawler, video_id, env):
  623. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  624. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, action="")
  625. return len(repeat_video)
  626. # 下载 / 上传
  627. @classmethod
  628. def download_publish(cls, log_type, crawler, user_dict, video_dict, rule_dict, env):
  629. Common.download_method(log_type=log_type, crawler=crawler, text='xigua_video',
  630. title=video_dict['video_title'], url=video_dict['video_url'])
  631. # 下载音频
  632. Common.download_method(log_type=log_type, crawler=crawler, text='xigua_audio',
  633. title=video_dict['video_title'], url=video_dict['audio_url'])
  634. # 合成音视频
  635. Common.video_compose(log_type=log_type, crawler=crawler,
  636. video_dir=f"./{crawler}/videos/{video_dict['video_title']}")
  637. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  638. try:
  639. if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
  640. # 删除视频文件夹
  641. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  642. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  643. return
  644. except FileNotFoundError:
  645. # 删除视频文件夹
  646. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  647. Common.logger(log_type, crawler).info("视频文件不存在,删除文件夹成功\n")
  648. return
  649. # 下载封面
  650. Common.download_method(log_type=log_type, crawler=crawler, text='cover',
  651. title=video_dict['video_title'], url=video_dict['cover_url'])
  652. # 保存视频信息至txt
  653. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  654. # 上传视频
  655. Common.logger(log_type, crawler).info("开始上传视频...")
  656. if env == "dev":
  657. oss_endpoint = "out"
  658. our_video_id = Publish.upload_and_publish(log_type=log_type,
  659. crawler=crawler,
  660. strategy="搜索抓取策略",
  661. our_uid=user_dict["uid"],
  662. env=env,
  663. oss_endpoint=oss_endpoint)
  664. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  665. else:
  666. oss_endpoint = "inner"
  667. our_video_id = Publish.upload_and_publish(log_type=log_type,
  668. crawler=crawler,
  669. strategy="搜索抓取策略",
  670. our_uid=user_dict["uid"],
  671. env=env,
  672. oss_endpoint=oss_endpoint)
  673. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  674. if our_video_id is None:
  675. try:
  676. # 删除视频文件夹
  677. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  678. return
  679. except FileNotFoundError:
  680. return
  681. # 视频信息保存数据库
  682. insert_sql = f""" insert into crawler_video(video_id,
  683. user_id,
  684. out_user_id,
  685. platform,
  686. strategy,
  687. out_video_id,
  688. video_title,
  689. cover_url,
  690. video_url,
  691. duration,
  692. publish_time,
  693. play_cnt,
  694. crawler_rule,
  695. width,
  696. height)
  697. values({our_video_id},
  698. {user_dict["uid"]},
  699. "{video_dict['user_id']}",
  700. "{cls.platform}",
  701. "搜索爬虫策略",
  702. "{video_dict['video_id']}",
  703. "{video_dict['video_title']}",
  704. "{video_dict['cover_url']}",
  705. "{video_dict['video_url']}",
  706. {int(video_dict['duration'])},
  707. "{video_dict['publish_time_str']}",
  708. {int(video_dict['play_cnt'])},
  709. '{json.dumps(rule_dict)}',
  710. {int(video_dict['video_width'])},
  711. {int(video_dict['video_height'])}) """
  712. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  713. MysqlHelper.update_values(log_type, crawler, insert_sql, env, action="")
  714. cls.download_cnt += 1
  715. Common.logger(log_type, crawler).info("视频信息写入数据库完成")
  716. # 视频信息写入飞书
  717. Feishu.insert_columns(log_type, crawler, "BUNvGC", "ROWS", 1, 2)
  718. values = [[user_dict["nick_name"],
  719. time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()))),
  720. "关键词搜索",
  721. video_dict['video_title'],
  722. str(video_dict['video_id']),
  723. our_video_link,
  724. video_dict['gid'],
  725. video_dict['play_cnt'],
  726. video_dict['comment_cnt'],
  727. video_dict['like_cnt'],
  728. video_dict['share_cnt'],
  729. video_dict['duration'],
  730. str(video_dict['video_width']) + '*' + str(video_dict['video_height']),
  731. video_dict['publish_time_str'],
  732. video_dict['user_name'],
  733. video_dict['user_id'],
  734. video_dict['avatar_url'],
  735. video_dict['cover_url'],
  736. video_dict['video_url'],
  737. video_dict['audio_url']]]
  738. time.sleep(0.5)
  739. Feishu.update_values(log_type, crawler, "BUNvGC", "E2:Z2", values)
  740. Common.logger(log_type, crawler).info('视频信息写入飞书完成\n')
  741. @classmethod
  742. def get_search_videos(cls, log_type, crawler, user_list, rule_dict, env):
  743. for user_dict in user_list:
  744. try:
  745. cls.download_cnt = 0
  746. Common.logger(log_type, crawler).info(f"开始抓取 {user_dict['nick_name']} 视频\n")
  747. cls.get_videoList(log_type=log_type,
  748. crawler=crawler,
  749. user_dict=user_dict,
  750. rule_dict=rule_dict,
  751. env=env)
  752. except Exception as e:
  753. Common.logger(log_type, crawler).error(f"抓取{user_dict['nick_name']}视频时异常:{e}\n")
  754. if __name__ == '__main__':
  755. pass