xigua_search_new.py 50 KB

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