xigua_follow.py 61 KB

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