xigua_follow.py 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021
  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.webdriver.common.by import By
  19. # from selenium import webdriver
  20. from lxml import etree
  21. sys.path.append(os.getcwd())
  22. from common.db import MysqlHelper
  23. from common.getuser import getUser
  24. from common.common import Common
  25. from common.feishu import Feishu
  26. from common.publish import Publish
  27. class Follow:
  28. # 个人主页视频翻页参数
  29. offset = 0
  30. platform = "西瓜视频"
  31. tag = "西瓜视频爬虫,定向爬虫策略"
  32. @classmethod
  33. def get_rule(cls, log_type, crawler):
  34. try:
  35. while True:
  36. rule_sheet = Feishu.get_values_batch(log_type, crawler, "4kxd31")
  37. if rule_sheet is None:
  38. Common.logger(log_type, crawler).warning("rule_sheet is None! 10秒后重新获取")
  39. time.sleep(10)
  40. continue
  41. rule_dict = {
  42. "play_cnt": int(rule_sheet[1][2]),
  43. "comment_cnt": int(rule_sheet[2][2]),
  44. "like_cnt": int(rule_sheet[3][2]),
  45. "duration": int(rule_sheet[4][2]),
  46. "publish_time": int(rule_sheet[5][2]),
  47. "video_width": int(rule_sheet[6][2]),
  48. "video_height": int(rule_sheet[7][2]),
  49. }
  50. return rule_dict
  51. except Exception as e:
  52. Common.logger(log_type, crawler).error(f"get_rule:{e}\n")
  53. # 下载规则
  54. @classmethod
  55. def download_rule(cls, video_info_dict, rule_dict):
  56. if video_info_dict['play_cnt'] >= rule_dict['play_cnt']:
  57. if video_info_dict['comment_cnt'] >= rule_dict['comment_cnt']:
  58. if video_info_dict['like_cnt'] >= rule_dict['like_cnt']:
  59. if video_info_dict['duration'] >= rule_dict['duration']:
  60. if video_info_dict['video_width'] >= rule_dict['video_width'] \
  61. or video_info_dict['video_height'] >= rule_dict['video_height']:
  62. return True
  63. else:
  64. return False
  65. else:
  66. return False
  67. else:
  68. return False
  69. else:
  70. return False
  71. else:
  72. return False
  73. # 过滤词库
  74. @classmethod
  75. def filter_words(cls, log_type, crawler):
  76. try:
  77. while True:
  78. filter_words_sheet = Feishu.get_values_batch(log_type, crawler, 'KGB4Hc')
  79. if filter_words_sheet is None:
  80. Common.logger(log_type, crawler).warning(f"filter_words_sheet:{filter_words_sheet} 10秒钟后重试")
  81. continue
  82. filter_words_list = []
  83. for x in filter_words_sheet:
  84. for y in x:
  85. if y is None:
  86. pass
  87. else:
  88. filter_words_list.append(y)
  89. return filter_words_list
  90. except Exception as e:
  91. Common.logger(log_type, crawler).error(f'filter_words异常:{e}\n')
  92. @classmethod
  93. def get_out_user_info(cls, log_type, crawler, out_uid):
  94. try:
  95. headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41',
  96. 'referer': f'https://www.ixigua.com/home/{out_uid}',
  97. 'Cookie': f'ixigua-a-s=1; support_webp=true; support_avif=false; csrf_session_id=a5355d954d3c63ed1ba35faada452b4d; __ac_signature={cls.random_signature()}; MONITOR_WEB_ID=67cb5099-a022-4ec3-bb8e-c4de6ba51dd0; s_v_web_id=verify_lef4i99x_32SosrdH_Qrtk_4LJn_8S7q_fhu16xe3s8ZV; tt_scid=QLJjPuHf6wxVqu6IIq6gHiJXQpVrCwrdhjH2zpm7-E3ZniE1RXBcP6M8b41FJOdo41e1; ttwid=1%7CHHtv2QqpSGuSu8r-zXF1QoWsvjmNi1SJrqOrZzg-UCY%7C1677047013%7C5866a444e5ae10a9df8c11551db75010fb77b657f214ccf84e503fae8d313d09; msToken=PerXJcDdIsZ6zXkGITsftXX4mDaVaW21GuqtzSVdctH46oXXT2GcELIs9f0XW2hunRzP6KVHLZaYElRvNYflLKUXih7lC27XKxs3HjdZiXPK9NQaoKbLfA==; ixigua-a-s=1',}
  98. url = f"https://www.ixigua.com/home/{out_uid}"
  99. urllib3.disable_warnings()
  100. s = requests.session()
  101. # max_retries=3 重试3次
  102. s.mount('http://', HTTPAdapter(max_retries=3))
  103. s.mount('https://', HTTPAdapter(max_retries=3))
  104. response = s.get(url=url, headers=headers, proxies=Common.tunnel_proxies(), verify=False, timeout=5).text
  105. html = etree.HTML(response)
  106. out_follow_str = html.xpath('//div[@class="userDetailV3__header__detail2"]/*[1]/span')[0].text.encode('raw_unicode_escape').decode()
  107. out_fans_str = html.xpath('//div[@class="userDetailV3__header__detail2"]/*[2]/span')[0].text.encode('raw_unicode_escape').decode()
  108. out_like_str = html.xpath('//div[@class="userDetailV3__header__detail2"]/*[3]/span')[0].text.encode('raw_unicode_escape').decode()
  109. out_avatar_url = f"""https:{html.xpath('//span[@class="component-avatar__inner"]//img/@src')[0]}"""
  110. if "万" in out_follow_str:
  111. out_follow = int(float(out_follow_str.split("万")[0])*10000)
  112. else:
  113. out_follow = int(out_follow_str.replace(",", ""))
  114. if "万" in out_fans_str:
  115. out_fans = int(float(out_fans_str.split("万")[0])*10000)
  116. else:
  117. out_fans = int(out_fans_str.replace(",", ""))
  118. if "万" in out_like_str:
  119. out_like = int(float(out_like_str.split("万")[0])*10000)
  120. else:
  121. out_like = int(out_like_str.replace(",", ""))
  122. out_user_dict = {
  123. "out_follow": out_follow,
  124. "out_fans": out_fans,
  125. "out_like": out_like,
  126. "out_avatar_url": out_avatar_url,
  127. }
  128. # for k, v in out_user_dict.items():
  129. # print(f"{k}:{v}")
  130. return out_user_dict
  131. except Exception as e:
  132. Common.logger(log_type, crawler).error(f"get_out_user_info:{e}\n")
  133. # 获取用户信息(字典格式). 注意:部分 user_id 字符类型是 int / str
  134. @classmethod
  135. def get_user_list(cls, log_type, crawler, sheetid, env, machine):
  136. try:
  137. while True:
  138. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  139. if user_sheet is None:
  140. Common.logger(log_type, crawler).warning(f"user_sheet:{user_sheet} 10秒钟后重试")
  141. continue
  142. our_user_list = []
  143. for i in range(1, len(user_sheet)):
  144. # for i in range(428, len(user_sheet)):
  145. out_uid = user_sheet[i][2]
  146. user_name = user_sheet[i][3]
  147. our_uid = user_sheet[i][6]
  148. our_user_link = user_sheet[i][7]
  149. if out_uid is None or user_name is None:
  150. Common.logger(log_type, crawler).info("空行\n")
  151. else:
  152. Common.logger(log_type, crawler).info(f"正在更新 {user_name} 用户信息\n")
  153. if our_uid is None:
  154. try:
  155. out_user_info = cls.get_out_user_info(log_type, crawler, out_uid)
  156. except Exception as e:
  157. continue
  158. out_user_dict = {
  159. "out_uid": out_uid,
  160. "user_name": user_name,
  161. "out_avatar_url": out_user_info["out_avatar_url"],
  162. "out_create_time": '',
  163. "out_tag": '',
  164. "out_play_cnt": 0,
  165. "out_fans": out_user_info["out_fans"],
  166. "out_follow": out_user_info["out_follow"],
  167. "out_friend": 0,
  168. "out_like": out_user_info["out_like"],
  169. "platform": cls.platform,
  170. "tag": cls.tag,
  171. }
  172. our_user_dict = getUser.create_user(log_type=log_type, crawler=crawler, out_user_dict=out_user_dict, env=env, machine=machine)
  173. our_uid = our_user_dict['our_uid']
  174. our_user_link = our_user_dict['our_user_link']
  175. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}', [[our_uid, our_user_link]])
  176. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!\n')
  177. our_user_list.append(our_user_dict)
  178. else:
  179. our_user_dict = {
  180. 'out_uid': out_uid,
  181. 'user_name': user_name,
  182. 'our_uid': our_uid,
  183. 'our_user_link': our_user_link,
  184. }
  185. our_user_list.append(our_user_dict)
  186. return our_user_list
  187. except Exception as e:
  188. Common.logger(log_type, crawler).error(f'get_user_id_from_feishu异常:{e}\n')
  189. @classmethod
  190. def random_signature(cls):
  191. src_digits = string.digits # string_数字
  192. src_uppercase = string.ascii_uppercase # string_大写字母
  193. src_lowercase = string.ascii_lowercase # string_小写字母
  194. digits_num = random.randint(1, 6)
  195. uppercase_num = random.randint(1, 26 - digits_num - 1)
  196. lowercase_num = 26 - (digits_num + uppercase_num)
  197. password = random.sample(src_digits, digits_num) + random.sample(src_uppercase, uppercase_num) + random.sample(
  198. src_lowercase, lowercase_num)
  199. random.shuffle(password)
  200. new_password = 'AAAAAAAAAA' + ''.join(password)[10:-4] + 'AAAB'
  201. new_password_start = new_password[0:18]
  202. new_password_end = new_password[-7:]
  203. if new_password[18] == '8':
  204. new_password = new_password_start + 'w' + new_password_end
  205. elif new_password[18] == '9':
  206. new_password = new_password_start + 'x' + new_password_end
  207. elif new_password[18] == '-':
  208. new_password = new_password_start + 'y' + new_password_end
  209. elif new_password[18] == '.':
  210. new_password = new_password_start + 'z' + new_password_end
  211. else:
  212. new_password = new_password_start + 'y' + new_password_end
  213. return new_password
  214. # @classmethod
  215. # def get_signature(cls, log_type, crawler, out_uid, machine):
  216. # try:
  217. # # 打印请求配置
  218. # ca = DesiredCapabilities.CHROME
  219. # ca["goog:loggingPrefs"] = {"performance": "ALL"}
  220. #
  221. # # 不打开浏览器运行
  222. # chrome_options = webdriver.ChromeOptions()
  223. # chrome_options.add_argument("--headless")
  224. # chrome_options.add_argument('--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')
  225. # chrome_options.add_argument("--no-sandbox")
  226. #
  227. # # driver初始化
  228. # if machine == 'aliyun' or machine == 'aliyun_hk':
  229. # driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
  230. # elif machine == 'macpro':
  231. # driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options,
  232. # service=Service('/Users/lieyunye/Downloads/chromedriver_v86/chromedriver'))
  233. # elif machine == 'macair':
  234. # driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options,
  235. # service=Service('/Users/piaoquan/Downloads/chromedriver'))
  236. # else:
  237. # driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service('/Users/wangkun/Downloads/chromedriver/chromedriver_v110/chromedriver'))
  238. # driver.implicitly_wait(10)
  239. # driver.get(f'https://www.ixigua.com/home/{out_uid}/')
  240. # time.sleep(3)
  241. # data_src = driver.find_elements(By.XPATH, '//img[@class="tt-img BU-MagicImage tt-img-loaded"]')[1].get_attribute("data-src")
  242. # signature = data_src.split("x-signature=")[-1]
  243. # return signature
  244. # except Exception as e:
  245. # Common.logger(log_type, crawler).error(f'get_signature异常:{e}\n')
  246. # 获取视频详情
  247. @classmethod
  248. def get_video_url(cls, log_type, crawler, gid):
  249. try:
  250. url = 'https://www.ixigua.com/api/mixVideo/information?'
  251. headers = {
  252. "accept-encoding": "gzip, deflate",
  253. "accept-language": "zh-CN,zh-Hans;q=0.9",
  254. "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
  255. "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15",
  256. "referer": "https://www.ixigua.com/7102614741050196520?logTag=0531c88ac04f38ab2c62",
  257. }
  258. params = {
  259. 'mixId': gid,
  260. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfC'
  261. 'NVVIOBNjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  262. 'X-Bogus': 'DFSzswVupYTANCJOSBk0P53WxM-r',
  263. '_signature': '_02B4Z6wo0000119LvEwAAIDCuktNZ0y5wkdfS7jAALThuOR8D9yWNZ.EmWHKV0WSn6Px'
  264. 'fPsH9-BldyxVje0f49ryXgmn7Tzk-swEHNb15TiGqa6YF.cX0jW8Eds1TtJOIZyfc9s5emH7gdWN94',
  265. }
  266. cookies = {
  267. 'ixigua-a-s': '1',
  268. 'msToken': 'IlG0wd0Pylyw9ghcYiB2YseUmTwrsrqqhXrbIcsSaTcLTJyVlbYJzk20zw3UO-CfrfCNVVIOB'
  269. 'NjIl7vfBoxnVUwO9ZyzAI3umSKsT5-pef_RRfQCJwmA',
  270. 'ttwid': '1%7C_yXQeHWwLZgCsgHClOwTCdYSOt_MjdOkgnPIkpi-Sr8%7C1661241238%7Cf57d0c5ef3f1d7'
  271. '6e049fccdca1ac54887c34d1f8731c8e51a49780ff0ceab9f8',
  272. 'tt_scid': 'QZ4l8KXDG0YAEaMCSbADdcybdKbUfG4BC6S4OBv9lpRS5VyqYLX2bIR8CTeZeGHR9ee3',
  273. 'MONITOR_WEB_ID': '0a49204a-7af5-4e96-95f0-f4bafb7450ad',
  274. '__ac_nonce': '06304878000964fdad287',
  275. '__ac_signature': '_02B4Z6wo00f017Rcr3AAAIDCUVxeW1tOKEu0fKvAAI4cvoYzV-wBhq7B6D8k0no7lb'
  276. 'FlvYoinmtK6UXjRIYPXnahUlFTvmWVtb77jsMkKAXzAEsLE56m36RlvL7ky.M3Xn52r9t1IEb7IR3ke8',
  277. 'ttcid': 'e56fabf6e85d4adf9e4d91902496a0e882',
  278. '_tea_utm_cache_1300': 'undefined',
  279. 'support_avif': 'false',
  280. 'support_webp': 'false',
  281. 'xiguavideopcwebid': '7134967546256016900',
  282. 'xiguavideopcwebid.sig': 'xxRww5R1VEMJN_dQepHorEu_eAc',
  283. }
  284. urllib3.disable_warnings()
  285. s = requests.session()
  286. # max_retries=3 重试3次
  287. s.mount('http://', HTTPAdapter(max_retries=3))
  288. s.mount('https://', HTTPAdapter(max_retries=3))
  289. response = s.get(url=url, headers=headers, params=params, cookies=cookies, verify=False, proxies=Common.tunnel_proxies(), timeout=5)
  290. response.close()
  291. if 'data' not in response.json() or response.json()['data'] == '':
  292. Common.logger(log_type, crawler).warning('get_video_info: response: {}', response)
  293. else:
  294. video_info = response.json()['data']['gidInformation']['packerData']['video']
  295. video_url_dict = {}
  296. # video_url
  297. if 'videoResource' not in video_info:
  298. video_url_dict["video_url"] = ''
  299. video_url_dict["audio_url"] = ''
  300. video_url_dict["video_width"] = 0
  301. video_url_dict["video_height"] = 0
  302. elif 'dash_120fps' in video_info['videoResource']:
  303. if "video_list" in video_info['videoResource']['dash_120fps'] and 'video_4' in video_info['videoResource']['dash_120fps']['video_list']:
  304. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_4']['backup_url_1']
  305. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_4']['backup_url_1']
  306. if len(video_url) % 3 == 1:
  307. video_url += '=='
  308. elif len(video_url) % 3 == 2:
  309. video_url += '='
  310. elif len(audio_url) % 3 == 1:
  311. audio_url += '=='
  312. elif len(audio_url) % 3 == 2:
  313. audio_url += '='
  314. video_url = base64.b64decode(video_url).decode('utf8')
  315. audio_url = base64.b64decode(audio_url).decode('utf8')
  316. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_4']['vwidth']
  317. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_4']['vheight']
  318. video_url_dict["video_url"] = video_url
  319. video_url_dict["audio_url"] = audio_url
  320. video_url_dict["video_width"] = video_width
  321. video_url_dict["video_height"] = video_height
  322. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_3' in video_info['videoResource']['dash_120fps']['video_list']:
  323. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_3']['backup_url_1']
  324. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_3']['backup_url_1']
  325. if len(video_url) % 3 == 1:
  326. video_url += '=='
  327. elif len(video_url) % 3 == 2:
  328. video_url += '='
  329. elif len(audio_url) % 3 == 1:
  330. audio_url += '=='
  331. elif len(audio_url) % 3 == 2:
  332. audio_url += '='
  333. video_url = base64.b64decode(video_url).decode('utf8')
  334. audio_url = base64.b64decode(audio_url).decode('utf8')
  335. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_3']['vwidth']
  336. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_3']['vheight']
  337. video_url_dict["video_url"] = video_url
  338. video_url_dict["audio_url"] = audio_url
  339. video_url_dict["video_width"] = video_width
  340. video_url_dict["video_height"] = video_height
  341. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_2' in video_info['videoResource']['dash_120fps']['video_list']:
  342. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_2']['backup_url_1']
  343. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_2']['backup_url_1']
  344. if len(video_url) % 3 == 1:
  345. video_url += '=='
  346. elif len(video_url) % 3 == 2:
  347. video_url += '='
  348. elif len(audio_url) % 3 == 1:
  349. audio_url += '=='
  350. elif len(audio_url) % 3 == 2:
  351. audio_url += '='
  352. video_url = base64.b64decode(video_url).decode('utf8')
  353. audio_url = base64.b64decode(audio_url).decode('utf8')
  354. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_2']['vwidth']
  355. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_2']['vheight']
  356. video_url_dict["video_url"] = video_url
  357. video_url_dict["audio_url"] = audio_url
  358. video_url_dict["video_width"] = video_width
  359. video_url_dict["video_height"] = video_height
  360. elif "video_list" in video_info['videoResource']['dash_120fps'] and 'video_1' in video_info['videoResource']['dash_120fps']['video_list']:
  361. video_url = video_info['videoResource']['dash_120fps']['video_list']['video_1']['backup_url_1']
  362. audio_url = video_info['videoResource']['dash_120fps']['video_list']['video_1']['backup_url_1']
  363. if len(video_url) % 3 == 1:
  364. video_url += '=='
  365. elif len(video_url) % 3 == 2:
  366. video_url += '='
  367. elif len(audio_url) % 3 == 1:
  368. audio_url += '=='
  369. elif len(audio_url) % 3 == 2:
  370. audio_url += '='
  371. video_url = base64.b64decode(video_url).decode('utf8')
  372. audio_url = base64.b64decode(audio_url).decode('utf8')
  373. video_width = video_info['videoResource']['dash_120fps']['video_list']['video_1']['vwidth']
  374. video_height = video_info['videoResource']['dash_120fps']['video_list']['video_1']['vheight']
  375. video_url_dict["video_url"] = video_url
  376. video_url_dict["audio_url"] = audio_url
  377. video_url_dict["video_width"] = video_width
  378. video_url_dict["video_height"] = video_height
  379. elif 'dynamic_video' in video_info['videoResource']['dash_120fps'] \
  380. and 'dynamic_video_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  381. and 'dynamic_audio_list' in video_info['videoResource']['dash_120fps']['dynamic_video'] \
  382. and len(video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list']) != 0 \
  383. and len(video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list']) != 0:
  384. video_url = video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1]['backup_url_1']
  385. audio_url = video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_audio_list'][-1]['backup_url_1']
  386. if len(video_url) % 3 == 1:
  387. video_url += '=='
  388. elif len(video_url) % 3 == 2:
  389. video_url += '='
  390. elif len(audio_url) % 3 == 1:
  391. audio_url += '=='
  392. elif len(audio_url) % 3 == 2:
  393. audio_url += '='
  394. video_url = base64.b64decode(video_url).decode('utf8')
  395. audio_url = base64.b64decode(audio_url).decode('utf8')
  396. video_width = video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1]['vwidth']
  397. video_height = video_info['videoResource']['dash_120fps']['dynamic_video']['dynamic_video_list'][-1]['vheight']
  398. video_url_dict["video_url"] = video_url
  399. video_url_dict["audio_url"] = audio_url
  400. video_url_dict["video_width"] = video_width
  401. video_url_dict["video_height"] = video_height
  402. else:
  403. video_url_dict["video_url"] = ''
  404. video_url_dict["audio_url"] = ''
  405. video_url_dict["video_width"] = 0
  406. video_url_dict["video_height"] = 0
  407. elif 'dash' in video_info['videoResource']:
  408. if "video_list" in video_info['videoResource']['dash'] and 'video_4' in video_info['videoResource']['dash']['video_list']:
  409. video_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  410. audio_url = video_info['videoResource']['dash']['video_list']['video_4']['backup_url_1']
  411. if len(video_url) % 3 == 1:
  412. video_url += '=='
  413. elif len(video_url) % 3 == 2:
  414. video_url += '='
  415. elif len(audio_url) % 3 == 1:
  416. audio_url += '=='
  417. elif len(audio_url) % 3 == 2:
  418. audio_url += '='
  419. video_url = base64.b64decode(video_url).decode('utf8')
  420. audio_url = base64.b64decode(audio_url).decode('utf8')
  421. video_width = video_info['videoResource']['dash']['video_list']['video_4']['vwidth']
  422. video_height = video_info['videoResource']['dash']['video_list']['video_4']['vheight']
  423. video_url_dict["video_url"] = video_url
  424. video_url_dict["audio_url"] = audio_url
  425. video_url_dict["video_width"] = video_width
  426. video_url_dict["video_height"] = video_height
  427. elif "video_list" in video_info['videoResource']['dash'] and 'video_3' in video_info['videoResource']['dash']['video_list']:
  428. video_url = video_info['videoResource']['dash']['video_list']['video_3']['backup_url_1']
  429. audio_url = video_info['videoResource']['dash']['video_list']['video_3']['backup_url_1']
  430. if len(video_url) % 3 == 1:
  431. video_url += '=='
  432. elif len(video_url) % 3 == 2:
  433. video_url += '='
  434. elif len(audio_url) % 3 == 1:
  435. audio_url += '=='
  436. elif len(audio_url) % 3 == 2:
  437. audio_url += '='
  438. video_url = base64.b64decode(video_url).decode('utf8')
  439. audio_url = base64.b64decode(audio_url).decode('utf8')
  440. video_width = video_info['videoResource']['dash']['video_list']['video_3']['vwidth']
  441. video_height = video_info['videoResource']['dash']['video_list']['video_3']['vheight']
  442. video_url_dict["video_url"] = video_url
  443. video_url_dict["audio_url"] = audio_url
  444. video_url_dict["video_width"] = video_width
  445. video_url_dict["video_height"] = video_height
  446. elif "video_list" in video_info['videoResource']['dash'] and 'video_2' in video_info['videoResource']['dash']['video_list']:
  447. video_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  448. audio_url = video_info['videoResource']['dash']['video_list']['video_2']['backup_url_1']
  449. if len(video_url) % 3 == 1:
  450. video_url += '=='
  451. elif len(video_url) % 3 == 2:
  452. video_url += '='
  453. elif len(audio_url) % 3 == 1:
  454. audio_url += '=='
  455. elif len(audio_url) % 3 == 2:
  456. audio_url += '='
  457. video_url = base64.b64decode(video_url).decode('utf8')
  458. audio_url = base64.b64decode(audio_url).decode('utf8')
  459. video_width = video_info['videoResource']['dash']['video_list']['video_2']['vwidth']
  460. video_height = video_info['videoResource']['dash']['video_list']['video_2']['vheight']
  461. video_url_dict["video_url"] = video_url
  462. video_url_dict["audio_url"] = audio_url
  463. video_url_dict["video_width"] = video_width
  464. video_url_dict["video_height"] = video_height
  465. elif "video_list" in video_info['videoResource']['dash'] and 'video_1' in video_info['videoResource']['dash']['video_list']:
  466. video_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  467. audio_url = video_info['videoResource']['dash']['video_list']['video_1']['backup_url_1']
  468. if len(video_url) % 3 == 1:
  469. video_url += '=='
  470. elif len(video_url) % 3 == 2:
  471. video_url += '='
  472. elif len(audio_url) % 3 == 1:
  473. audio_url += '=='
  474. elif len(audio_url) % 3 == 2:
  475. audio_url += '='
  476. video_url = base64.b64decode(video_url).decode('utf8')
  477. audio_url = base64.b64decode(audio_url).decode('utf8')
  478. video_width = video_info['videoResource']['dash']['video_list']['video_1']['vwidth']
  479. video_height = video_info['videoResource']['dash']['video_list']['video_1']['vheight']
  480. video_url_dict["video_url"] = video_url
  481. video_url_dict["audio_url"] = audio_url
  482. video_url_dict["video_width"] = video_width
  483. video_url_dict["video_height"] = video_height
  484. elif 'dynamic_video' in video_info['videoResource']['dash'] \
  485. and 'dynamic_video_list' in video_info['videoResource']['dash']['dynamic_video'] \
  486. and 'dynamic_audio_list' in video_info['videoResource']['dash']['dynamic_video'] \
  487. and len(video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list']) != 0 \
  488. and len(video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list']) != 0:
  489. video_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1]['backup_url_1']
  490. audio_url = video_info['videoResource']['dash']['dynamic_video']['dynamic_audio_list'][-1]['backup_url_1']
  491. if len(video_url) % 3 == 1:
  492. video_url += '=='
  493. elif len(video_url) % 3 == 2:
  494. video_url += '='
  495. elif len(audio_url) % 3 == 1:
  496. audio_url += '=='
  497. elif len(audio_url) % 3 == 2:
  498. audio_url += '='
  499. video_url = base64.b64decode(video_url).decode('utf8')
  500. audio_url = base64.b64decode(audio_url).decode('utf8')
  501. video_width = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1]['vwidth']
  502. video_height = video_info['videoResource']['dash']['dynamic_video']['dynamic_video_list'][-1]['vheight']
  503. video_url_dict["video_url"] = video_url
  504. video_url_dict["audio_url"] = audio_url
  505. video_url_dict["video_width"] = video_width
  506. video_url_dict["video_height"] = video_height
  507. else:
  508. video_url_dict["video_url"] = ''
  509. video_url_dict["audio_url"] = ''
  510. video_url_dict["video_width"] = 0
  511. video_url_dict["video_height"] = 0
  512. elif 'normal' in video_info['videoResource']:
  513. if "video_list" in video_info['videoResource']['normal'] and 'video_4' in \
  514. video_info['videoResource']['normal']['video_list']:
  515. video_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  516. audio_url = video_info['videoResource']['normal']['video_list']['video_4']['backup_url_1']
  517. if len(video_url) % 3 == 1:
  518. video_url += '=='
  519. elif len(video_url) % 3 == 2:
  520. video_url += '='
  521. elif len(audio_url) % 3 == 1:
  522. audio_url += '=='
  523. elif len(audio_url) % 3 == 2:
  524. audio_url += '='
  525. video_url = base64.b64decode(video_url).decode('utf8')
  526. audio_url = base64.b64decode(audio_url).decode('utf8')
  527. video_width = video_info['videoResource']['normal']['video_list']['video_4']['vwidth']
  528. video_height = video_info['videoResource']['normal']['video_list']['video_4']['vheight']
  529. video_url_dict["video_url"] = video_url
  530. video_url_dict["audio_url"] = audio_url
  531. video_url_dict["video_width"] = video_width
  532. video_url_dict["video_height"] = video_height
  533. elif "video_list" in video_info['videoResource']['normal'] and 'video_3' in \
  534. video_info['videoResource']['normal']['video_list']:
  535. video_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  536. audio_url = video_info['videoResource']['normal']['video_list']['video_3']['backup_url_1']
  537. if len(video_url) % 3 == 1:
  538. video_url += '=='
  539. elif len(video_url) % 3 == 2:
  540. video_url += '='
  541. elif len(audio_url) % 3 == 1:
  542. audio_url += '=='
  543. elif len(audio_url) % 3 == 2:
  544. audio_url += '='
  545. video_url = base64.b64decode(video_url).decode('utf8')
  546. audio_url = base64.b64decode(audio_url).decode('utf8')
  547. video_width = video_info['videoResource']['normal']['video_list']['video_3']['vwidth']
  548. video_height = video_info['videoResource']['normal']['video_list']['video_3']['vheight']
  549. video_url_dict["video_url"] = video_url
  550. video_url_dict["audio_url"] = audio_url
  551. video_url_dict["video_width"] = video_width
  552. video_url_dict["video_height"] = video_height
  553. elif "video_list" in video_info['videoResource']['normal'] and 'video_2' in \
  554. video_info['videoResource']['normal']['video_list']:
  555. video_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  556. audio_url = video_info['videoResource']['normal']['video_list']['video_2']['backup_url_1']
  557. if len(video_url) % 3 == 1:
  558. video_url += '=='
  559. elif len(video_url) % 3 == 2:
  560. video_url += '='
  561. elif len(audio_url) % 3 == 1:
  562. audio_url += '=='
  563. elif len(audio_url) % 3 == 2:
  564. audio_url += '='
  565. video_url = base64.b64decode(video_url).decode('utf8')
  566. audio_url = base64.b64decode(audio_url).decode('utf8')
  567. video_width = video_info['videoResource']['normal']['video_list']['video_2']['vwidth']
  568. video_height = video_info['videoResource']['normal']['video_list']['video_2']['vheight']
  569. video_url_dict["video_url"] = video_url
  570. video_url_dict["audio_url"] = audio_url
  571. video_url_dict["video_width"] = video_width
  572. video_url_dict["video_height"] = video_height
  573. elif "video_list" in video_info['videoResource']['normal'] and 'video_1' in \
  574. video_info['videoResource']['normal']['video_list']:
  575. video_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  576. audio_url = video_info['videoResource']['normal']['video_list']['video_1']['backup_url_1']
  577. if len(video_url) % 3 == 1:
  578. video_url += '=='
  579. elif len(video_url) % 3 == 2:
  580. video_url += '='
  581. elif len(audio_url) % 3 == 1:
  582. audio_url += '=='
  583. elif len(audio_url) % 3 == 2:
  584. audio_url += '='
  585. video_url = base64.b64decode(video_url).decode('utf8')
  586. audio_url = base64.b64decode(audio_url).decode('utf8')
  587. video_width = video_info['videoResource']['normal']['video_list']['video_1']['vwidth']
  588. video_height = video_info['videoResource']['normal']['video_list']['video_1']['vheight']
  589. video_url_dict["video_url"] = video_url
  590. video_url_dict["audio_url"] = audio_url
  591. video_url_dict["video_width"] = video_width
  592. video_url_dict["video_height"] = video_height
  593. elif 'dynamic_video' in video_info['videoResource']['normal'] \
  594. and 'dynamic_video_list' in video_info['videoResource']['normal']['dynamic_video'] \
  595. and 'dynamic_audio_list' in video_info['videoResource']['normal']['dynamic_video'] \
  596. and len(video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list']) != 0 \
  597. and len(video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list']) != 0:
  598. video_url = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  599. 'backup_url_1']
  600. audio_url = video_info['videoResource']['normal']['dynamic_video']['dynamic_audio_list'][-1][
  601. 'backup_url_1']
  602. if len(video_url) % 3 == 1:
  603. video_url += '=='
  604. elif len(video_url) % 3 == 2:
  605. video_url += '='
  606. elif len(audio_url) % 3 == 1:
  607. audio_url += '=='
  608. elif len(audio_url) % 3 == 2:
  609. audio_url += '='
  610. video_url = base64.b64decode(video_url).decode('utf8')
  611. audio_url = base64.b64decode(audio_url).decode('utf8')
  612. video_width = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  613. 'vwidth']
  614. video_height = video_info['videoResource']['normal']['dynamic_video']['dynamic_video_list'][-1][
  615. 'vheight']
  616. video_url_dict["video_url"] = video_url
  617. video_url_dict["audio_url"] = audio_url
  618. video_url_dict["video_width"] = video_width
  619. video_url_dict["video_height"] = video_height
  620. else:
  621. video_url_dict["video_url"] = ''
  622. video_url_dict["audio_url"] = ''
  623. video_url_dict["video_width"] = 0
  624. video_url_dict["video_height"] = 0
  625. else:
  626. video_url_dict["video_url"] = ''
  627. video_url_dict["audio_url"] = ''
  628. video_url_dict["video_width"] = 0
  629. video_url_dict["video_height"] = 0
  630. return video_url_dict
  631. except Exception as e:
  632. Common.logger(log_type, crawler).error(f'get_video_url:{e}\n')
  633. @classmethod
  634. def get_videolist(cls, log_type, crawler, strategy, our_uid, out_uid, oss_endpoint, env, machine):
  635. try:
  636. signature = cls.random_signature()
  637. while True:
  638. url = "https://www.ixigua.com/api/videov2/author/new_video_list?"
  639. params = {
  640. 'to_user_id': str(out_uid),
  641. 'offset': str(cls.offset),
  642. 'limit': '30',
  643. 'maxBehotTime': '0',
  644. 'order': 'new',
  645. 'isHome': '0',
  646. # 'msToken': 'G0eRzNkw189a8TLaXjc6nTHVMQwh9XcxVAqTbGKi7iPJdQcLwS3-XRrJ3MZ7QBfqErpxp3EX1WtvWOIcZ3NIgr41hgcd-v64so_RRj3YCRw1UsKW8mIssNLlIMspsg==',
  647. # 'X-Bogus': 'DFSzswVuEkUANjW9ShFTgR/F6qHt',
  648. '_signature': signature,
  649. }
  650. headers = {
  651. # 'authority': 'www.ixigua.com',
  652. # 'accept': 'application/json, text/plain, */*',
  653. # 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  654. # 'cache-control': 'no-cache',
  655. # 'cookie': f'MONITOR_WEB_ID=7168304743566296612; __ac_signature={signature}; ixigua-a-s=1; support_webp=true; support_avif=false; csrf_session_id=a5355d954d3c63ed1ba35faada452b4d; msToken=G0eRzNkw189a8TLaXjc6nTHVMQwh9XcxVAqTbGKi7iPJdQcLwS3-XRrJ3MZ7QBfqErpxp3EX1WtvWOIcZ3NIgr41hgcd-v64so_RRj3YCRw1UsKW8mIssNLlIMspsg==; tt_scid=o4agqz7u9SKPwfBoPt6S82Cw0q.9KDtqmNe0JHxMqmpxNHQWq1BmrQdgVU6jEoX7ed99; ttwid=1%7CHHtv2QqpSGuSu8r-zXF1QoWsvjmNi1SJrqOrZzg-UCY%7C1676618894%7Cee5ad95378275f282f230a7ffa9947ae7eff40d0829c5a2568672a6dc90a1c96; ixigua-a-s=1',
  656. # 'pragma': 'no-cache',
  657. 'referer': f'https://www.ixigua.com/home/{out_uid}/video/?preActiveKey=hotsoon&list_entrance=userdetail',
  658. # 'sec-ch-ua': '"Chromium";v="110", "Not A(Brand";v="24", "Microsoft Edge";v="110"',
  659. # 'sec-ch-ua-mobile': '?0',
  660. # 'sec-ch-ua-platform': '"macOS"',
  661. # 'sec-fetch-dest': 'empty',
  662. # 'sec-fetch-mode': 'cors',
  663. # 'sec-fetch-site': 'same-origin',
  664. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36 Edg/110.0.1587.41',
  665. # 'x-secsdk-csrf-token': '00010000000119e3f9454d1dcbb288704cda1960f241e2d19bd21f2fd283520c3615a990ac5a17448bfbb902a249'
  666. }
  667. urllib3.disable_warnings()
  668. s = requests.session()
  669. # max_retries=3 重试3次
  670. s.mount('http://', HTTPAdapter(max_retries=3))
  671. s.mount('https://', HTTPAdapter(max_retries=3))
  672. response = s.get(url=url, headers=headers, params=params, proxies=Common.tunnel_proxies(), verify=False, timeout=5)
  673. response.close()
  674. cls.offset += 30
  675. if response.status_code != 200:
  676. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.text}\n")
  677. cls.offset = 0
  678. return
  679. elif 'data' not in response.text:
  680. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.text}\n")
  681. cls.offset = 0
  682. return
  683. elif not response.json()["data"]['videoList']:
  684. Common.logger(log_type, crawler).warning(f"get_videolist_response:{response.json()}\n")
  685. cls.offset = 0
  686. return
  687. else:
  688. videoList = response.json()['data']['videoList']
  689. for i in range(len(videoList)):
  690. # video_title
  691. if 'title' not in videoList[i]:
  692. video_title = 0
  693. else:
  694. video_title = videoList[i]['title'].strip().replace('手游', '') \
  695. .replace('/', '').replace('\/', '').replace('\n', '')
  696. # video_id
  697. if 'video_id' not in videoList[i]:
  698. video_id = 0
  699. else:
  700. video_id = videoList[i]['video_id']
  701. # gid
  702. if 'gid' not in videoList[i]:
  703. gid = 0
  704. else:
  705. gid = videoList[i]['gid']
  706. # play_cnt
  707. if 'video_detail_info' not in videoList[i]:
  708. play_cnt = 0
  709. elif 'video_watch_count' not in videoList[i]['video_detail_info']:
  710. play_cnt = 0
  711. else:
  712. play_cnt = videoList[i]['video_detail_info']['video_watch_count']
  713. # comment_cnt
  714. if 'comment_count' not in videoList[i]:
  715. comment_cnt = 0
  716. else:
  717. comment_cnt = videoList[i]['comment_count']
  718. # like_cnt
  719. if 'digg_count' not in videoList[i]:
  720. like_cnt = 0
  721. else:
  722. like_cnt = videoList[i]['digg_count']
  723. # share_cnt
  724. share_cnt = 0
  725. # video_duration
  726. if 'video_duration' not in videoList[i]:
  727. video_duration = 0
  728. else:
  729. video_duration = int(videoList[i]['video_duration'])
  730. # send_time
  731. if 'publish_time' not in videoList[i]:
  732. publish_time = 0
  733. else:
  734. publish_time = videoList[i]['publish_time']
  735. publish_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(publish_time))
  736. # is_top
  737. if 'is_top' not in videoList[i]:
  738. is_top = 0
  739. else:
  740. is_top = videoList[i]['is_top']
  741. # user_name
  742. if 'user_info' not in videoList[i]:
  743. user_name = 0
  744. elif 'name' not in videoList[i]['user_info']:
  745. user_name = 0
  746. else:
  747. user_name = videoList[i]['user_info']['name']
  748. # user_id
  749. if 'user_info' not in videoList[i]:
  750. user_id = 0
  751. elif 'user_id' not in videoList[i]['user_info']:
  752. user_id = 0
  753. else:
  754. user_id = videoList[i]['user_info']['user_id']
  755. # avatar_url
  756. if 'user_info' not in videoList[i]:
  757. avatar_url = 0
  758. elif 'avatar_url' not in videoList[i]['user_info']:
  759. avatar_url = 0
  760. else:
  761. avatar_url = videoList[i]['user_info']['avatar_url']
  762. # cover_url
  763. if 'video_detail_info' not in videoList[i]:
  764. cover_url = 0
  765. elif 'detail_video_large_image' not in videoList[i]['video_detail_info']:
  766. cover_url = 0
  767. elif 'url' in videoList[i]['video_detail_info']['detail_video_large_image']:
  768. cover_url = videoList[i]['video_detail_info']['detail_video_large_image']['url']
  769. else:
  770. cover_url = videoList[i]['video_detail_info']['detail_video_large_image']['url_list'][0]['url']
  771. Common.logger(log_type, crawler).info(f'---开始读取规则---')
  772. rule_dict = cls.get_rule(log_type, crawler)
  773. Common.logger(log_type, crawler).info(f'---读取规则完成---')
  774. if gid == 0 or video_id == 0 or cover_url == 0:
  775. Common.logger(log_type, crawler).info('无效视频\n')
  776. elif is_top is True and int(time.time()) - int(publish_time) > 3600 * 24 * rule_dict['publish_time']:
  777. Common.logger(log_type, crawler).info(f'置顶视频,且发布时间:{publish_time_str} 超过{rule_dict["publish_time"]}天\n')
  778. elif int(time.time()) - int(publish_time) > 3600 * 24 * rule_dict['publish_time']:
  779. Common.logger(log_type, crawler).info(f'发布时间:{publish_time_str}超过{rule_dict["publish_time"]}天\n')
  780. cls.offset = 0
  781. return
  782. else:
  783. video_url_dict = cls.get_video_url(log_type, crawler, gid)
  784. video_url = video_url_dict["video_url"]
  785. audio_url = video_url_dict["audio_url"]
  786. video_width = video_url_dict["video_width"]
  787. video_height = video_url_dict["video_height"]
  788. video_dict = {'video_title': video_title,
  789. 'video_id': video_id,
  790. 'gid': gid,
  791. 'play_cnt': play_cnt,
  792. 'comment_cnt': comment_cnt,
  793. 'like_cnt': like_cnt,
  794. 'share_cnt': share_cnt,
  795. 'video_width': video_width,
  796. 'video_height': video_height,
  797. 'duration': video_duration,
  798. 'publish_time_stamp': publish_time,
  799. 'publish_time_str': publish_time_str,
  800. 'is_top': is_top,
  801. 'user_name': user_name,
  802. 'user_id': user_id,
  803. 'avatar_url': avatar_url,
  804. 'cover_url': cover_url,
  805. 'audio_url': audio_url,
  806. 'video_url': video_url,
  807. 'session': signature}
  808. for k, v in video_dict.items():
  809. Common.logger(log_type, crawler).info(f"{k}:{v}")
  810. cls.download_publish(log_type=log_type,
  811. crawler=crawler,
  812. video_dict=video_dict,
  813. rule_dict=rule_dict,
  814. strategy=strategy,
  815. our_uid=our_uid,
  816. oss_endpoint=oss_endpoint,
  817. env=env,
  818. machine=machine)
  819. except Exception as e:
  820. Common.logger(log_type, crawler).error(f"get_videolist:{e}\n")
  821. @classmethod
  822. def repeat_video(cls, log_type, crawler, video_id, env, machine):
  823. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  824. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  825. return len(repeat_video)
  826. # 下载 / 上传
  827. @classmethod
  828. def download_publish(cls, log_type, crawler, strategy, video_dict, rule_dict, our_uid, oss_endpoint, env, machine):
  829. try:
  830. if cls.download_rule(video_dict, rule_dict) is False:
  831. Common.logger(log_type, crawler).info('不满足抓取规则\n')
  832. elif any(word if word in video_dict['video_title'] else False for word in cls.filter_words(log_type, crawler)) is True:
  833. Common.logger(log_type, crawler).info('标题已中过滤词:{}\n', video_dict['video_title'])
  834. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env, machine) != 0:
  835. Common.logger(log_type, crawler).info('视频已下载\n')
  836. # elif str(video_dict['video_id']) in [x for y in Feishu.get_values_batch(log_type, 'xigua', 'e075e9') for x in y]:
  837. # Common.logger(log_type, crawler).info('视频已下载\n')
  838. # elif str(video_dict['video_id']) in [x for y in Feishu.get_values_batch(log_type, 'xigua', '3Ul6wZ') for x in y]:
  839. # Common.logger(log_type, crawler).info('视频已下载\n')
  840. # elif str(video_dict['video_id']) in [x for y in Feishu.get_values_batch(log_type, 'xigua', 'QOWqMo') for x in y]:
  841. # Common.logger(log_type, crawler).info('视频已下载\n')
  842. # elif str(video_dict['video_id']) in [x for y in Feishu.get_values_batch(log_type, 'xigua', 'wjhpDs') for x in y]:
  843. # Common.logger(log_type, crawler).info('视频已存在\n')
  844. else:
  845. # 下载视频
  846. Common.download_method(log_type=log_type, crawler=crawler, text='xigua_video', title=video_dict['video_title'], url=video_dict['video_url'])
  847. # 下载音频
  848. Common.download_method(log_type=log_type, crawler=crawler, text='xigua_audio', title=video_dict['video_title'], url=video_dict['audio_url'])
  849. # 合成音视频
  850. Common.video_compose(log_type=log_type, crawler=crawler, video_dir=f"./{crawler}/videos/{video_dict['video_title']}")
  851. md_title = md5(video_dict['video_title'].encode('utf8')).hexdigest()
  852. if os.path.getsize(f"./{crawler}/videos/{md_title}/video.mp4") == 0:
  853. # 删除视频文件夹
  854. shutil.rmtree(f"./{crawler}/videos/{md_title}")
  855. Common.logger(log_type, crawler).info("视频size=0,删除成功\n")
  856. return
  857. # ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  858. # if ffmpeg_dict is None or ffmpeg_dict['size'] == 0:
  859. # Common.logger(log_type, crawler).warning(f"下载的视频无效,已删除\n")
  860. # # 删除视频文件夹
  861. # shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  862. # return
  863. # 下载封面
  864. Common.download_method(log_type=log_type, crawler=crawler, text='cover', title=video_dict['video_title'], url=video_dict['cover_url'])
  865. # 保存视频信息至txt
  866. Common.save_video_info(log_type=log_type, crawler=crawler, video_dict=video_dict)
  867. # 上传视频
  868. Common.logger(log_type, crawler).info("开始上传视频...")
  869. our_video_id = Publish.upload_and_publish(log_type=log_type,
  870. crawler=crawler,
  871. strategy=strategy,
  872. our_uid=our_uid,
  873. env=env,
  874. oss_endpoint=oss_endpoint)
  875. if env == 'dev':
  876. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  877. else:
  878. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  879. Common.logger(log_type, crawler).info("视频上传完成")
  880. if our_video_id is None:
  881. # 删除视频文件夹
  882. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}")
  883. return
  884. # 视频写入飞书
  885. Feishu.insert_columns(log_type, 'xigua', "e075e9", "ROWS", 1, 2)
  886. upload_time = int(time.time())
  887. values = [[time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(upload_time)),
  888. "定向榜",
  889. video_dict['video_title'],
  890. str(video_dict['video_id']),
  891. our_video_link,
  892. video_dict['gid'],
  893. video_dict['play_cnt'],
  894. video_dict['comment_cnt'],
  895. video_dict['like_cnt'],
  896. video_dict['share_cnt'],
  897. video_dict['duration'],
  898. str(video_dict['video_width']) + '*' + str(video_dict['video_height']),
  899. video_dict['publish_time_str'],
  900. video_dict['user_name'],
  901. video_dict['user_id'],
  902. video_dict['avatar_url'],
  903. video_dict['cover_url'],
  904. video_dict['video_url'],
  905. video_dict['audio_url']]]
  906. time.sleep(1)
  907. Feishu.update_values(log_type, 'xigua', "e075e9", "F2:Z2", values)
  908. Common.logger(log_type, crawler).info(f"视频已保存至云文档\n")
  909. # 视频信息保存数据库
  910. insert_sql = f""" insert into crawler_video(video_id,
  911. user_id,
  912. out_user_id,
  913. platform,
  914. strategy,
  915. out_video_id,
  916. video_title,
  917. cover_url,
  918. video_url,
  919. duration,
  920. publish_time,
  921. play_cnt,
  922. crawler_rule,
  923. width,
  924. height)
  925. values({our_video_id},
  926. {our_uid},
  927. "{video_dict['user_id']}",
  928. "{cls.platform}",
  929. "定向爬虫策略",
  930. "{video_dict['video_id']}",
  931. "{video_dict['video_title']}",
  932. "{video_dict['cover_url']}",
  933. "{video_dict['video_url']}",
  934. {int(video_dict['duration'])},
  935. "{video_dict['publish_time_str']}",
  936. {int(video_dict['play_cnt'])},
  937. '{json.dumps(rule_dict)}',
  938. {int(video_dict['video_width'])},
  939. {int(video_dict['video_height'])}) """
  940. Common.logger(log_type, crawler).info(f"insert_sql:{insert_sql}")
  941. MysqlHelper.update_values(log_type, crawler, insert_sql, env, machine)
  942. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  943. except Exception as e:
  944. Common.logger(log_type, crawler).error(f'download_publish异常:{e}\n')
  945. @classmethod
  946. def get_follow_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine):
  947. try:
  948. user_list = cls.get_user_list(log_type=log_type, crawler=crawler, sheetid="5tlTYB", env=env, machine=machine)
  949. for user in user_list:
  950. out_uid = user["out_uid"]
  951. user_name = user["user_name"]
  952. our_uid = user["our_uid"]
  953. Common.logger(log_type, crawler).info(f"开始抓取 {user_name} 用户主页视频\n")
  954. cls.get_videolist(log_type=log_type,
  955. crawler=crawler,
  956. strategy=strategy,
  957. our_uid=our_uid,
  958. out_uid=out_uid,
  959. oss_endpoint=oss_endpoint,
  960. env=env,
  961. machine=machine)
  962. cls.offset = 0
  963. time.sleep(1)
  964. except Exception as e:
  965. Common.logger(log_type, crawler).error(f"get_follow_videos:{e}\n")
  966. if __name__ == '__main__':
  967. Follow.get_follow_videos('follow','xigua','定向抓取策略', 'inner','prod', 'aliyun')