youtube_follow.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  1. # -*- coding: utf-8 -*-
  2. # @Author: wangkun
  3. # @Time: 2023/2/3
  4. """
  5. YouTube 定向榜
  6. 1. 发布时间<=1个月
  7. 2. 10分钟>=时长>=1分钟
  8. """
  9. import os
  10. import re
  11. import shutil
  12. import sys
  13. import time
  14. import json
  15. # import emoji
  16. import requests
  17. from selenium import webdriver
  18. from selenium.webdriver.chrome.service import Service
  19. from selenium.webdriver.common.by import By
  20. from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
  21. sys.path.append(os.getcwd())
  22. from common.common import Common
  23. from common.db import MysqlHelper
  24. from common.feishu import Feishu
  25. from common.users import Users
  26. from common.publish import Publish
  27. from common.translate import Translate
  28. class Follow:
  29. # 翻页参数
  30. continuation = ''
  31. # 抓取平台
  32. platform = 'youtube'
  33. @classmethod
  34. def get_browse_id(cls, log_type, crawler, out_user_id, machine):
  35. """
  36. 获取每个用户的 browse_id
  37. :param log_type: 日志
  38. :param crawler: 哪款爬虫
  39. :param out_user_id: 站外用户 UID
  40. :param machine: 部署机器,阿里云填写 aliyun / aliyun_hk,线下分别填写 macpro,macair,local
  41. :return: browse_id
  42. """
  43. try:
  44. # 打印请求配置
  45. ca = DesiredCapabilities.CHROME
  46. ca["goog:loggingPrefs"] = {"performance": "ALL"}
  47. # 不打开浏览器运行
  48. chrome_options = webdriver.ChromeOptions()
  49. chrome_options.add_argument("--headless")
  50. 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')
  51. chrome_options.add_argument("--no-sandbox")
  52. # driver初始化
  53. if machine == 'aliyun' or machine == 'aliyun_hk':
  54. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options)
  55. elif machine == 'macpro':
  56. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service('/Users/lieyunye/Downloads/chromedriver_v86/chromedriver'))
  57. elif machine == 'macair':
  58. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service('/Users/piaoquan/Downloads/chromedriver'))
  59. else:
  60. driver = webdriver.Chrome(desired_capabilities=ca, options=chrome_options, service=Service('/Users/wangkun/Downloads/chromedriver/chromedriver_v110/chromedriver'))
  61. driver.implicitly_wait(10)
  62. url = f'https://www.youtube.com/{out_user_id}/videos'
  63. driver.get(url)
  64. # driver.save_screenshot("./1.png")
  65. # 向上滑动 1000 个像素
  66. # driver.execute_script('window.scrollBy(0, 2000)')
  67. # driver.save_screenshot("./2.png")
  68. time.sleep(3)
  69. accept_btns = driver.find_elements(By.XPATH, '//span[text()="全部接受"]')
  70. accept_btns_eng = driver.find_elements(By.XPATH, '//span[text()="Accept all"]')
  71. if len(accept_btns) != 0:
  72. accept_btns[0].click()
  73. time.sleep(2)
  74. elif len(accept_btns_eng) != 0:
  75. accept_btns_eng[0].click()
  76. time.sleep(2)
  77. browse_id = driver.find_element(By.XPATH, '//meta[@itemprop="channelId"]').get_attribute('content')
  78. driver.quit()
  79. return browse_id
  80. except Exception as e:
  81. Common.logger(log_type, crawler).error(f'get_browse_id异常:{e}\n')
  82. @classmethod
  83. def get_out_user_info(cls, log_type, crawler, browse_id, out_user_id):
  84. """
  85. 获取站外用户信息
  86. :param log_type: 日志
  87. :param crawler: 哪款爬虫
  88. :param browse_id: browse_id
  89. :param out_user_id: 站外用户 UID
  90. :return: out_user_dict = {'out_user_name': 站外用户昵称,
  91. 'out_avatar_url': 站外用户头像,
  92. 'out_fans': 站外用户粉丝量,
  93. 'out_play_cnt': 站外用户总播放量,
  94. 'out_create_time': 站外用户创建时间}
  95. """
  96. try:
  97. url = "https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
  98. payload = json.dumps({
  99. "context": {
  100. "client": {
  101. "hl": "zh-CN",
  102. "gl": "US",
  103. "remoteHost": "38.93.247.21",
  104. "deviceMake": "Apple",
  105. "deviceModel": "",
  106. "visitorData": "CgtraDZfVnB4NXdIWSjL1IKfBg%3D%3D",
  107. "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36,gzip(gfe)",
  108. "clientName": "WEB",
  109. "clientVersion": "2.20230201.01.00",
  110. "osName": "Macintosh",
  111. "osVersion": "10_15_7",
  112. "originalUrl": f"https://www.youtube.com/{out_user_id}/about",
  113. "screenPixelDensity": 1,
  114. "platform": "DESKTOP",
  115. "clientFormFactor": "UNKNOWN_FORM_FACTOR",
  116. "configInfo": {
  117. "appInstallData": "CMvUgp8GEKLsrgUQzN-uBRC41K4FENfkrgUQsvWuBRDkoP4SELiLrgUQo_muBRDn964FENnprgUQlPiuBRC2nP4SEPuj_hIQ4tSuBRCJ6K4FEILdrgUQh92uBRD-7q4FEMz1rgUQ76P-EhDJya4FEJan_hIQkfj8Eg%3D%3D"
  118. },
  119. "screenDensityFloat": 1,
  120. "timeZone": "Asia/Shanghai",
  121. "browserName": "Chrome",
  122. "browserVersion": "109.0.0.0",
  123. "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
  124. "deviceExperimentId": "ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EMvUgp8GGOmU7Z4G",
  125. "screenWidthPoints": 805,
  126. "screenHeightPoints": 969,
  127. "utcOffsetMinutes": 480,
  128. "userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT",
  129. "memoryTotalKbytes": "8000000",
  130. "mainAppWebInfo": {
  131. "graftUrl": f"/{out_user_id}/about",
  132. "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_CAN_BE_INSTALLED",
  133. "webDisplayMode": "WEB_DISPLAY_MODE_FULLSCREEN",
  134. "isWebNativeShareAvailable": True
  135. }
  136. },
  137. "user": {
  138. "lockedSafetyMode": False
  139. },
  140. "request": {
  141. "useSsl": True,
  142. "internalExperimentFlags": [],
  143. "consistencyTokenJars": []
  144. },
  145. "clickTracking": {
  146. "clickTrackingParams": "CBMQ8JMBGAoiEwjY34r0rYD9AhURSEwIHfHZAak="
  147. },
  148. "adSignalsInfo": {
  149. "params": [
  150. {
  151. "key": "dt",
  152. "value": "1675668045032"
  153. },
  154. {
  155. "key": "flash",
  156. "value": "0"
  157. },
  158. {
  159. "key": "frm",
  160. "value": "0"
  161. },
  162. {
  163. "key": "u_tz",
  164. "value": "480"
  165. },
  166. {
  167. "key": "u_his",
  168. "value": "1"
  169. },
  170. {
  171. "key": "u_h",
  172. "value": "1080"
  173. },
  174. {
  175. "key": "u_w",
  176. "value": "1920"
  177. },
  178. {
  179. "key": "u_ah",
  180. "value": "1080"
  181. },
  182. {
  183. "key": "u_aw",
  184. "value": "1920"
  185. },
  186. {
  187. "key": "u_cd",
  188. "value": "24"
  189. },
  190. {
  191. "key": "bc",
  192. "value": "31"
  193. },
  194. {
  195. "key": "bih",
  196. "value": "969"
  197. },
  198. {
  199. "key": "biw",
  200. "value": "805"
  201. },
  202. {
  203. "key": "brdim",
  204. "value": "-269,-1080,-269,-1080,1920,-1080,1920,1080,805,969"
  205. },
  206. {
  207. "key": "vis",
  208. "value": "1"
  209. },
  210. {
  211. "key": "wgl",
  212. "value": "true"
  213. },
  214. {
  215. "key": "ca_type",
  216. "value": "image"
  217. }
  218. ],
  219. "bid": "ANyPxKqvCBKtjNeHQ6uTC7sKj2ZwIvEkk3oRlmdU7H_soRJWLc4IQCkqMVP68RR-Xae0h3nMdOKYOtVh_Yb2OYr4znd60I5j7A"
  220. }
  221. },
  222. "browseId": browse_id,
  223. "params": "EgVhYm91dPIGBAoCEgA%3D"
  224. })
  225. headers = {
  226. 'authority': 'www.youtube.com',
  227. 'accept': '*/*',
  228. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  229. 'cache-control': 'no-cache',
  230. 'content-type': 'application/json',
  231. 'cookie': 'VISITOR_INFO1_LIVE=kh6_Vpx5wHY; YSC=UupqFrWvAR0; DEVICE_INFO=ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EOmU7Z4GGOmU7Z4G; GPS=1; PREF=tz=Asia.Shanghai; ST-h076le=itct=CBMQ8JMBGAoiEwjY34r0rYD9AhURSEwIHfHZAak%3D&csn=MC45NDM2MjgyNzM1ODE5NDAz&endpoint=%7B%22clickTrackingParams%22%3A%22CBMQ8JMBGAoiEwjY34r0rYD9AhURSEwIHfHZAak%3D%22%2C%22commandMetadata%22%3A%7B%22webCommandMetadata%22%3A%7B%22url%22%3A%22%2F%40weitravel%2Fabout%22%2C%22webPageType%22%3A%22WEB_PAGE_TYPE_CHANNEL%22%2C%22rootVe%22%3A3611%2C%22apiUrl%22%3A%22%2Fyoutubei%2Fv1%2Fbrowse%22%7D%7D%2C%22browseEndpoint%22%3A%7B%22browseId%22%3A%22UC08jgxf119fzynp2uHCvZIg%22%2C%22params%22%3A%22EgVhYm91dPIGBAoCEgA%253D%22%2C%22canonicalBaseUrl%22%3A%22%2F%40weitravel%22%7D%7D',
  232. 'origin': 'https://www.youtube.com',
  233. 'pragma': 'no-cache',
  234. 'referer': f'https://www.youtube.com/{out_user_id}/videos',
  235. 'sec-ch-ua': '"Not_A Brand";v="99", "Chromium";v="109", "Google Chrome";v="109.0.5414.87"',
  236. 'sec-ch-ua-arch': '"arm"',
  237. 'sec-ch-ua-bitness': '"64"',
  238. 'sec-ch-ua-full-version': '"109.0.1518.52"',
  239. 'sec-ch-ua-full-version-list': '"Not_A Brand";v="99.0.0.0", "Microsoft Edge";v="109.0.1518.52", "Chromium";v="109.0.5414.87"',
  240. 'sec-ch-ua-mobile': '?0',
  241. 'sec-ch-ua-model': '',
  242. 'sec-ch-ua-platform': '"macOS"',
  243. 'sec-ch-ua-platform-version': '"12.4.0"',
  244. 'sec-ch-ua-wow64': '?0',
  245. 'sec-fetch-dest': 'empty',
  246. 'sec-fetch-mode': 'same-origin',
  247. 'sec-fetch-site': 'same-origin',
  248. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
  249. 'x-goog-visitor-id': 'CgtraDZfVnB4NXdIWSjL1IKfBg%3D%3D',
  250. 'x-youtube-bootstrap-logged-in': 'false',
  251. 'x-youtube-client-name': '1',
  252. 'x-youtube-client-version': '2.20230201.01.00'
  253. }
  254. response = requests.post(url=url, headers=headers, data=payload)
  255. if response.status_code != 200:
  256. Common.logger(log_type, crawler).warning(f'get_out_user_info:{response.text}\n')
  257. elif 'contents' not in response.text or 'header' not in response.text:
  258. Common.logger(log_type, crawler).warning(f'get_out_user_info:{response.text}\n')
  259. elif 'c4TabbedHeaderRenderer' not in response.json()['header']:
  260. Common.logger(log_type, crawler).warning(f'get_out_user_info:{response.json()["header"]}\n')
  261. elif 'twoColumnBrowseResultsRenderer' not in response.json()['contents']:
  262. Common.logger(log_type, crawler).warning(f'get_out_user_info:{response.json()}\n')
  263. elif 'tabs' not in response.json()['contents']['twoColumnBrowseResultsRenderer']:
  264. Common.logger(log_type, crawler).warning(f"get_out_user_info:{response.json()['contents']['twoColumnBrowseResultsRenderer']}\n")
  265. else:
  266. header = response.json()['header']['c4TabbedHeaderRenderer']
  267. tabs = response.json()['contents']['twoColumnBrowseResultsRenderer']['tabs']
  268. for i in range(len(tabs)):
  269. if 'tabRenderer' not in tabs[i]:
  270. title = ''
  271. elif 'title' not in tabs[i]['tabRenderer']:
  272. title = ''
  273. else:
  274. title = tabs[i]['tabRenderer']['title']
  275. if title == '简介':
  276. if 'tabRenderer' not in tabs[i]:
  277. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]}\n")
  278. elif 'content' not in tabs[i]['tabRenderer']:
  279. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']}\n")
  280. elif 'sectionListRenderer' not in tabs[i]['tabRenderer']['content']:
  281. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']}\n")
  282. elif 'contents' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']:
  283. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']}\n")
  284. elif len(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents']) == 0:
  285. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']}\n")
  286. elif 'itemSectionRenderer' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]:
  287. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]}\n")
  288. elif 'contents' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']:
  289. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']}\n")
  290. elif len(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents']) == 0:
  291. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']}\n")
  292. elif 'channelAboutFullMetadataRenderer' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]:
  293. Common.logger(log_type, crawler).warning(f"get_out_user_info:{tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]}\n")
  294. else:
  295. # 站外用户昵称
  296. if 'title' not in header and 'title' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  297. out_user_name = ''
  298. elif 'title' in header:
  299. out_user_name = header['title']
  300. elif 'simpleText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['title']:
  301. out_user_name = ''
  302. else:
  303. out_user_name = tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['title']['simpleText']
  304. # 站外用户头像
  305. if 'avatar' not in header and 'avatar' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  306. out_avatar_url = ''
  307. elif 'thumbnails' not in header['avatar'] and 'thumbnails' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['avatar']:
  308. out_avatar_url = ''
  309. elif len(header['avatar']['thumbnails']) == 0 and len(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['avatar']['thumbnails']) == 0:
  310. out_avatar_url = ''
  311. elif 'url' not in header['avatar']['thumbnails'][-1] and 'url' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['avatar']['thumbnails'][-1]:
  312. out_avatar_url = ''
  313. elif 'url' in header['avatar']['thumbnails'][-1]:
  314. out_avatar_url = header['avatar']['thumbnails'][-1]['url']
  315. else:
  316. out_avatar_url = tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['avatar']['thumbnails'][-1]['url']
  317. # 站外用户粉丝
  318. if 'subscriberCountText' not in header:
  319. out_fans = 0
  320. elif 'accessibility' not in header['subscriberCountText']:
  321. out_fans = 0
  322. elif 'accessibilityData' not in header['subscriberCountText']['accessibility']:
  323. out_fans = 0
  324. elif 'label' not in header['subscriberCountText']['accessibility']['accessibilityData']:
  325. out_fans = 0
  326. else:
  327. out_fans = header['subscriberCountText']['accessibility']['accessibilityData']['label']
  328. if '万' in out_fans:
  329. out_fans = int(float(out_fans.split('万')[0])*10000)
  330. elif "位" in out_fans:
  331. out_fans = int(out_fans.split('位')[0].replace(",", ""))
  332. else:
  333. pass
  334. # 站外用户总播放量
  335. if 'viewCountText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  336. out_play_cnt = 0
  337. elif 'simpleText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['viewCountText']:
  338. out_play_cnt = 0
  339. else:
  340. out_play_cnt = int(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['viewCountText']['simpleText'].split('次')[0].replace(',', ''))
  341. # 站外用户注册时间
  342. if 'joinedDateText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  343. out_create_time = ''
  344. elif 'runs' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']:
  345. out_create_time = ''
  346. elif len(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs']) == 0:
  347. out_create_time = ''
  348. elif 'text' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs'][0]:
  349. out_create_time = ''
  350. else:
  351. out_create_time = tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs'][0]['text'].replace('年', '-').replace('月', '-').replace('日', '')
  352. out_user_dict = {
  353. 'out_user_name': out_user_name,
  354. 'out_avatar_url': out_avatar_url,
  355. 'out_fans': out_fans,
  356. 'out_play_cnt': out_play_cnt,
  357. 'out_create_time': out_create_time,
  358. }
  359. # print(out_user_dict)
  360. return out_user_dict
  361. except Exception as e:
  362. Common.logger(log_type, crawler).error(f'get_out_user_info异常:{e}\n')
  363. @classmethod
  364. def get_user_from_feishu(cls, log_type, crawler, sheetid, env, machine):
  365. """
  366. 补全飞书用户表信息,并返回
  367. :param log_type: 日志
  368. :param crawler: 哪款爬虫
  369. :param sheetid: 飞书表
  370. :param env: 正式环境:prod,测试环境:dev
  371. :param machine: 部署机器,阿里云填写 aliyun,aliyun_hk ,线下分别填写 macpro,macair,local
  372. :return: user_list
  373. """
  374. try:
  375. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  376. user_list = []
  377. for i in range(1, len(user_sheet)):
  378. out_uid = user_sheet[i][2]
  379. user_name = user_sheet[i][3]
  380. browse_id = user_sheet[i][5]
  381. our_uid = user_sheet[i][6]
  382. Common.logger(log_type, crawler).info(f"正在更新 {user_name} 用户信息\n")
  383. # 获取站外browse_id,并写入飞书
  384. if browse_id is None:
  385. browse_id = cls.get_browse_id(log_type, crawler, out_uid, machine)
  386. if browse_id is None:
  387. Common.logger(log_type, crawler).warning('browse_id is None !')
  388. else:
  389. Feishu.update_values(log_type, crawler, sheetid, f'F{i+1}:F{i+1}', [[browse_id]])
  390. Common.logger(log_type, crawler).info(f'browse_id写入成功:{browse_id}')
  391. # 站内 UID 为空,且数据库中(youtube+out_user_id)返回数量 == 0,则创建新的站内账号
  392. if our_uid is None:
  393. sql = f""" select * from crawler_user where platform="{cls.platform}" and out_user_id="{out_uid}" """
  394. our_user_info = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  395. # 数据库中(youtube + out_user_id)返回数量 == 0,则创建站内账号UID,并写入定向账号飞书表。并结合站外用户信息,一并写入爬虫账号数据库
  396. if our_user_info is None or len(our_user_info) == 0:
  397. # 获取站外账号信息,写入数据库
  398. out_user_dict = cls.get_out_user_info(log_type, crawler, browse_id, out_uid)
  399. out_avatar_url = out_user_dict['out_avatar_url']
  400. out_create_time = out_user_dict['out_create_time']
  401. out_play_cnt = out_user_dict['out_play_cnt']
  402. out_fans = out_user_dict['out_fans']
  403. tag = 'youtube爬虫,定向爬虫策略'
  404. # 创建站内账号
  405. create_user_dict = {
  406. 'nickName': user_name,
  407. 'avatarUrl': out_avatar_url,
  408. 'tagName': tag,
  409. }
  410. our_uid = Users.create_user(log_type, crawler, create_user_dict, env)
  411. Common.logger(log_type, crawler).info(f'新创建的站内UID:{our_uid}')
  412. if env == 'dev':
  413. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  414. else:
  415. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  416. Common.logger(log_type, crawler).info(f'站内用户主页链接:{our_user_link}')
  417. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}', [[our_uid, our_user_link]])
  418. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!')
  419. sql = f""" insert into crawler_user(user_id,
  420. out_user_id,
  421. out_user_name,
  422. out_avatar_url,
  423. out_create_time,
  424. out_play_cnt,
  425. out_fans,
  426. platform,
  427. tag)
  428. values({our_uid},
  429. "{out_uid}",
  430. "{user_name}",
  431. "{out_avatar_url}",
  432. "{out_create_time}",
  433. {out_play_cnt},
  434. {out_fans},
  435. "{cls.platform}",
  436. "{tag}") """
  437. Common.logger(log_type, crawler).info(f'sql:{sql}')
  438. MysqlHelper.update_values(log_type, crawler, sql, env, machine)
  439. Common.logger(log_type, crawler).info('用户信息插入数据库成功!\n')
  440. # 数据库中(youtube + out_user_id)返回数量 != 0,则直接把数据库中的站内 UID 写入飞书
  441. else:
  442. our_uid = our_user_info[0][1]
  443. if 'env' == 'prod':
  444. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  445. else:
  446. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  447. Common.logger(log_type, crawler).info(f'站内用户主页链接:{our_user_link}')
  448. Feishu.update_values(log_type, crawler, sheetid, f'G{i+1}:H{i+1}', [[our_uid, our_user_link]])
  449. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!\n')
  450. user_dict = {
  451. 'out_user_id': out_uid,
  452. 'out_user_name': user_name,
  453. 'out_browse_id': browse_id,
  454. 'our_user_id': our_uid,
  455. }
  456. user_list.append(user_dict)
  457. return user_list
  458. except Exception as e:
  459. Common.logger(log_type, crawler).error(f"get_user_from_feishu异常:{e}\n")
  460. @classmethod
  461. def get_feeds(cls, log_type, crawler, browse_id, out_uid):
  462. """
  463. 获取个人主页视频列表
  464. :param log_type: 日志
  465. :param crawler: 哪款爬虫
  466. :param browse_id: 每个用户主页的请求参数中唯一值
  467. :param out_uid: 站外用户UID
  468. :return: video_list
  469. """
  470. url = "https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
  471. payload = json.dumps({
  472. "context": {
  473. "client": {
  474. "hl": "zh-CN",
  475. "gl": "US",
  476. "remoteHost": "38.93.247.21",
  477. "deviceMake": "Apple",
  478. "deviceModel": "",
  479. "visitorData": "CgtraDZfVnB4NXdIWSi6mIOfBg%3D%3D",
  480. "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36,gzip(gfe)",
  481. "clientName": "WEB",
  482. "clientVersion": "2.20230201.01.00",
  483. "osName": "Macintosh",
  484. "osVersion": "10_15_7",
  485. "originalUrl": f"https://www.youtube.com/{out_uid}/videos",
  486. "platform": "DESKTOP",
  487. "clientFormFactor": "UNKNOWN_FORM_FACTOR",
  488. "configInfo": {
  489. "appInstallData": "CLqYg58GEInorgUQuIuuBRCU-K4FENfkrgUQuNSuBRC2nP4SEPuj_hIQ5_euBRCy9a4FEKLsrgUQt-CuBRDi1K4FEILdrgUQh92uBRDM364FEP7urgUQzPWuBRDZ6a4FEOSg_hIQo_muBRDvo_4SEMnJrgUQlqf-EhCR-PwS"
  490. },
  491. "timeZone": "Asia/Shanghai",
  492. "browserName": "Chrome",
  493. "browserVersion": "109.0.0.0",
  494. "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
  495. "deviceExperimentId": "ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09ELqYg58GGOmU7Z4G",
  496. "screenWidthPoints": 944,
  497. "screenHeightPoints": 969,
  498. "screenPixelDensity": 1,
  499. "screenDensityFloat": 1,
  500. "utcOffsetMinutes": 480,
  501. "userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT",
  502. "memoryTotalKbytes": "8000000",
  503. "mainAppWebInfo": {
  504. "graftUrl": f"/{out_uid}/videos",
  505. "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_CAN_BE_INSTALLED",
  506. "webDisplayMode": "WEB_DISPLAY_MODE_FULLSCREEN",
  507. "isWebNativeShareAvailable": True
  508. }
  509. },
  510. "user": {
  511. "lockedSafetyMode": False
  512. },
  513. "request": {
  514. "useSsl": True,
  515. "internalExperimentFlags": [],
  516. "consistencyTokenJars": []
  517. },
  518. "clickTracking": {
  519. "clickTrackingParams": "CBcQ8JMBGAYiEwiNhIXX9IL9AhUFSUwIHWnnDks="
  520. },
  521. "adSignalsInfo": {
  522. "params": [
  523. {
  524. "key": "dt",
  525. "value": "1675676731048"
  526. },
  527. {
  528. "key": "flash",
  529. "value": "0"
  530. },
  531. {
  532. "key": "frm",
  533. "value": "0"
  534. },
  535. {
  536. "key": "u_tz",
  537. "value": "480"
  538. },
  539. {
  540. "key": "u_his",
  541. "value": "4"
  542. },
  543. {
  544. "key": "u_h",
  545. "value": "1080"
  546. },
  547. {
  548. "key": "u_w",
  549. "value": "1920"
  550. },
  551. {
  552. "key": "u_ah",
  553. "value": "1080"
  554. },
  555. {
  556. "key": "u_aw",
  557. "value": "1920"
  558. },
  559. {
  560. "key": "u_cd",
  561. "value": "24"
  562. },
  563. {
  564. "key": "bc",
  565. "value": "31"
  566. },
  567. {
  568. "key": "bih",
  569. "value": "969"
  570. },
  571. {
  572. "key": "biw",
  573. "value": "944"
  574. },
  575. {
  576. "key": "brdim",
  577. "value": "-269,-1080,-269,-1080,1920,-1080,1920,1080,944,969"
  578. },
  579. {
  580. "key": "vis",
  581. "value": "1"
  582. },
  583. {
  584. "key": "wgl",
  585. "value": "true"
  586. },
  587. {
  588. "key": "ca_type",
  589. "value": "image"
  590. }
  591. ],
  592. "bid": "ANyPxKpfiaAf-DBzNeKLgkceMEA9UIeCWFRTRm4AQMCuejhI3PGwDB1jizQIX60YcEYtt_CX7tZWAbYerQ-rWLvV7y_KCLkBww"
  593. }
  594. },
  595. "browseId": browse_id,
  596. "params": "EgZ2aWRlb3PyBgQKAjoA",
  597. "continuation": cls.continuation
  598. })
  599. headers = {
  600. 'authority': 'www.youtube.com',
  601. 'accept': '*/*',
  602. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  603. 'cache-control': 'no-cache',
  604. 'content-type': 'application/json',
  605. 'cookie': 'VISITOR_INFO1_LIVE=kh6_Vpx5wHY; YSC=UupqFrWvAR0; DEVICE_INFO=ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EOmU7Z4GGOmU7Z4G; PREF=tz=Asia.Shanghai; ST-1kg1gfd=itct=CBcQ8JMBGAYiEwiNhIXX9IL9AhUFSUwIHWnnDks%3D&csn=MC4zNzI3MDcwMDA1Mjg4NzE5Ng..&endpoint=%7B%22clickTrackingParams%22%3A%22CBcQ8JMBGAYiEwiNhIXX9IL9AhUFSUwIHWnnDks%3D%22%2C%22commandMetadata%22%3A%7B%22webCommandMetadata%22%3A%7B%22url%22%3A%22%2F%40chinatravel5971%2Fvideos%22%2C%22webPageType%22%3A%22WEB_PAGE_TYPE_CHANNEL%22%2C%22rootVe%22%3A3611%2C%22apiUrl%22%3A%22%2Fyoutubei%2Fv1%2Fbrowse%22%7D%7D%2C%22browseEndpoint%22%3A%7B%22browseId%22%3A%22UCpLXnfBCNhj8KLnt54RQMKA%22%2C%22params%22%3A%22EgZ2aWRlb3PyBgQKAjoA%22%2C%22canonicalBaseUrl%22%3A%22%2F%40chinatravel5971%22%7D%7D',
  606. 'origin': 'https://www.youtube.com',
  607. 'pragma': 'no-cache',
  608. 'referer': f'https://www.youtube.com/{out_uid}/featured',
  609. 'sec-ch-ua': '"Not_A Brand";v="99", "Chromium";v="109", "Google Chrome";v="109.0.5414.87"',
  610. 'sec-ch-ua-arch': '"arm"',
  611. 'sec-ch-ua-bitness': '"64"',
  612. 'sec-ch-ua-full-version': '"109.0.1518.52"',
  613. 'sec-ch-ua-full-version-list': '"Not_A Brand";v="99.0.0.0", "Microsoft Edge";v="109.0.1518.52", "Chromium";v="109.0.5414.87"',
  614. 'sec-ch-ua-mobile': '?0',
  615. 'sec-ch-ua-model': '',
  616. 'sec-ch-ua-platform': '"macOS"',
  617. 'sec-ch-ua-platform-version': '"12.4.0"',
  618. 'sec-ch-ua-wow64': '?0',
  619. 'sec-fetch-dest': 'empty',
  620. 'sec-fetch-mode': 'same-origin',
  621. 'sec-fetch-site': 'same-origin',
  622. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
  623. 'x-goog-visitor-id': 'CgtraDZfVnB4NXdIWSi6mIOfBg%3D%3D',
  624. 'x-youtube-bootstrap-logged-in': 'false',
  625. 'x-youtube-client-name': '1',
  626. 'x-youtube-client-version': '2.20230201.01.00'
  627. }
  628. try:
  629. response = requests.post(url=url, headers=headers, data=payload)
  630. # Common.logger(log_type, crawler).info(f"get_feeds_response:{response.json()}\n")
  631. cls.continuation = response.json()['trackingParams']
  632. if response.status_code != 200:
  633. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.text}\n')
  634. elif 'continuationContents' not in response.text and 'onResponseReceivedActions' not in response.text:
  635. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.text}\n')
  636. elif 'continuationContents' in response.json():
  637. # Common.logger(log_type, crawler).info("'continuationContents' in response.json()\n")
  638. if 'richGridContinuation' not in response.json()['continuationContents']:
  639. # Common.logger(log_type, crawler).warning(f"'richGridContinuation' not in response.json()['continuationContents']\n")
  640. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["continuationContents"]}\n')
  641. elif 'contents' not in response.json()['continuationContents']['richGridContinuation']:
  642. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["continuationContents"]["richGridContinuation"]}\n')
  643. elif 'contents' in response.json()["continuationContents"]["richGridContinuation"]:
  644. feeds = response.json()["continuationContents"]["richGridContinuation"]['contents']
  645. return feeds
  646. elif 'onResponseReceivedActions' in response.json():
  647. Common.logger(log_type, crawler).info("'onResponseReceivedActions' in response.json()\n")
  648. if len(response.json()['onResponseReceivedActions']) == 0:
  649. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"]}\n')
  650. elif 'appendContinuationItemsAction' not in response.json()['onResponseReceivedActions'][0]:
  651. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]}\n')
  652. elif 'continuationItems' not in response.json()['onResponseReceivedActions'][0]['appendContinuationItemsAction']:
  653. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]}\n')
  654. elif len(response.json()['onResponseReceivedActions'][0]['appendContinuationItemsAction']['continuationItems']) == 0:
  655. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]["continuationItems"]}\n')
  656. else:
  657. feeds = response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]["continuationItems"]
  658. return feeds
  659. else:
  660. Common.logger(log_type, crawler).info('feeds is None\n')
  661. except Exception as e:
  662. Common.logger(log_type, crawler).error(f'get_feeds异常:{e}\n')
  663. @classmethod
  664. def get_videos(cls, log_type, crawler, strategy, oss_endpoint, env, browse_id, out_uid, our_uid, machine):
  665. try:
  666. while True:
  667. feeds = cls.get_feeds(log_type, crawler, browse_id, out_uid)
  668. for i in range(len(feeds)):
  669. if 'richItemRenderer' not in feeds[i]:
  670. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]}\n')
  671. return
  672. elif 'content' not in feeds[i]['richItemRenderer']:
  673. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]}\n')
  674. return
  675. elif 'videoRenderer' not in feeds[i]['richItemRenderer']['content']:
  676. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]["content"]}\n')
  677. return
  678. elif 'videoId' not in feeds[i]["richItemRenderer"]["content"]['videoRenderer']:
  679. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]["content"]["videoRenderer"]}\n')
  680. return
  681. else:
  682. video_id = feeds[i]["richItemRenderer"]["content"]['videoRenderer']['videoId']
  683. video_dict = cls.get_video_info(log_type, crawler, out_uid, video_id, machine)
  684. # 发布时间<=30天
  685. publish_time = int(time.mktime(time.strptime(video_dict['publish_time'], "%Y-%m-%d")))
  686. if int(time.time()) - publish_time <= 3600*24*180:
  687. cls.download_publish(log_type, crawler, video_dict, strategy, our_uid, env, oss_endpoint, machine)
  688. else:
  689. Common.logger(log_type, crawler).info('发布时间超过180天\n')
  690. return
  691. except Exception as e:
  692. Common.logger(log_type, crawler).error(f"get_videos异常:{e}\n")
  693. @classmethod
  694. def filter_emoji(cls, title):
  695. # 过滤表情
  696. try:
  697. co = re.compile(u'[\U00010000-\U0010ffff]')
  698. except re.error:
  699. co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
  700. return co.sub("", title)
  701. @classmethod
  702. def get_video_info(cls, log_type, crawler, out_uid, video_id, machine):
  703. try:
  704. url = "https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
  705. payload = json.dumps({
  706. "context": {
  707. "client": {
  708. "hl": "zh-CN",
  709. "gl": "US",
  710. "remoteHost": "38.93.247.21",
  711. "deviceMake": "Apple",
  712. "deviceModel": "",
  713. "visitorData": "CgtraDZfVnB4NXdIWSjkzoefBg%3D%3D",
  714. "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36,gzip(gfe)",
  715. "clientName": "WEB",
  716. "clientVersion": "2.20230201.01.00",
  717. "osName": "Macintosh",
  718. "osVersion": "10_15_7",
  719. "originalUrl": f"https://www.youtube.com/watch?v={video_id}",
  720. "platform": "DESKTOP",
  721. "clientFormFactor": "UNKNOWN_FORM_FACTOR",
  722. "configInfo": {
  723. "appInstallData": "COTOh58GEPuj_hIQ1-SuBRC4i64FEMzfrgUQgt2uBRCi7K4FEOLUrgUQzPWuBRCKgK8FEOSg_hIQtpz-EhDa6a4FEP7urgUQieiuBRDn964FELjUrgUQlPiuBRCH3a4FELfgrgUQ76P-EhDJya4FEJan_hIQkfj8Eg%3D%3D"
  724. },
  725. "timeZone": "Asia/Shanghai",
  726. "browserName": "Chrome",
  727. "browserVersion": "109.0.0.0",
  728. "acceptHeader": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
  729. "deviceExperimentId": "ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EOTOh58GGOmU7Z4G",
  730. "screenWidthPoints": 1037,
  731. "screenHeightPoints": 969,
  732. "screenPixelDensity": 1,
  733. "screenDensityFloat": 1,
  734. "utcOffsetMinutes": 480,
  735. "userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT",
  736. "memoryTotalKbytes": "8000000",
  737. "clientScreen": "WATCH",
  738. "mainAppWebInfo": {
  739. "graftUrl": f"/watch?v={video_id}",
  740. "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_CAN_BE_INSTALLED",
  741. "webDisplayMode": "WEB_DISPLAY_MODE_FULLSCREEN",
  742. "isWebNativeShareAvailable": True
  743. }
  744. },
  745. "user": {
  746. "lockedSafetyMode": False
  747. },
  748. "request": {
  749. "useSsl": True,
  750. "internalExperimentFlags": [],
  751. "consistencyTokenJars": []
  752. },
  753. "clickTracking": {
  754. "clickTrackingParams": "CIwBEKQwGAYiEwipncqx3IL9AhXs4cQKHbKZDO4yB3JlbGF0ZWRInsS1qbGFtIlUmgEFCAEQ-B0="
  755. },
  756. "adSignalsInfo": {
  757. "params": [
  758. {
  759. "key": "dt",
  760. "value": "1675749222611"
  761. },
  762. {
  763. "key": "flash",
  764. "value": "0"
  765. },
  766. {
  767. "key": "frm",
  768. "value": "0"
  769. },
  770. {
  771. "key": "u_tz",
  772. "value": "480"
  773. },
  774. {
  775. "key": "u_his",
  776. "value": "3"
  777. },
  778. {
  779. "key": "u_h",
  780. "value": "1080"
  781. },
  782. {
  783. "key": "u_w",
  784. "value": "1920"
  785. },
  786. {
  787. "key": "u_ah",
  788. "value": "1080"
  789. },
  790. {
  791. "key": "u_aw",
  792. "value": "1920"
  793. },
  794. {
  795. "key": "u_cd",
  796. "value": "24"
  797. },
  798. {
  799. "key": "bc",
  800. "value": "31"
  801. },
  802. {
  803. "key": "bih",
  804. "value": "969"
  805. },
  806. {
  807. "key": "biw",
  808. "value": "1037"
  809. },
  810. {
  811. "key": "brdim",
  812. "value": "-269,-1080,-269,-1080,1920,-1080,1920,1080,1037,969"
  813. },
  814. {
  815. "key": "vis",
  816. "value": "1"
  817. },
  818. {
  819. "key": "wgl",
  820. "value": "true"
  821. },
  822. {
  823. "key": "ca_type",
  824. "value": "image"
  825. }
  826. ],
  827. "bid": "ANyPxKop8SijebwUCq4ZfKbJwlSjVQa_RTdS6c6a6WPYpCKnxpWCJ33B1SzRuSXjSfH9O2MhURebAs0CngRg6B4nOjBpeJDKgA"
  828. }
  829. },
  830. "videoId": str(video_id),
  831. "playbackContext": {
  832. "contentPlaybackContext": {
  833. "currentUrl": f"/watch?v={video_id}",
  834. "vis": 0,
  835. "splay": False,
  836. "autoCaptionsDefaultOn": False,
  837. "autonavState": "STATE_NONE",
  838. "html5Preference": "HTML5_PREF_WANTS",
  839. "signatureTimestamp": 19394,
  840. "referer": f"https://www.youtube.com/watch?v={video_id}",
  841. "lactMilliseconds": "-1",
  842. "watchAmbientModeContext": {
  843. "watchAmbientModeEnabled": True
  844. }
  845. }
  846. },
  847. "racyCheckOk": False,
  848. "contentCheckOk": False
  849. })
  850. headers = {
  851. 'authority': 'www.youtube.com',
  852. 'accept': '*/*',
  853. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  854. 'cache-control': 'no-cache',
  855. 'content-type': 'application/json',
  856. 'cookie': f'VISITOR_INFO1_LIVE=kh6_Vpx5wHY; YSC=UupqFrWvAR0; DEVICE_INFO=ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EOmU7Z4GGOmU7Z4G; PREF=tz=Asia.Shanghai; ST-180dxzo=itct=CIwBEKQwGAYiEwipncqx3IL9AhXs4cQKHbKZDO4yB3JlbGF0ZWRInsS1qbGFtIlUmgEFCAEQ-B0%3D&csn=MC41MTQ1NTQzMTE3NTA4MjY0&endpoint=%7B%22clickTrackingParams%22%3A%22CIwBEKQwGAYiEwipncqx3IL9AhXs4cQKHbKZDO4yB3JlbGF0ZWRInsS1qbGFtIlUmgEFCAEQ-B0%3D%22%2C%22commandMetadata%22%3A%7B%22webCommandMetadata%22%3A%7B%22url%22%3A%22%2Fwatch%3Fv%3D{video_id}%22%2C%22webPageType%22%3A%22WEB_PAGE_TYPE_WATCH%22%2C%22rootVe%22%3A3832%7D%7D%2C%22watchEndpoint%22%3A%7B%22videoId%22%3A%22{video_id}%22%2C%22nofollow%22%3Atrue%2C%22watchEndpointSupportedOnesieConfig%22%3A%7B%22html5PlaybackOnesieConfig%22%3A%7B%22commonConfig%22%3A%7B%22url%22%3A%22https%3A%2F%2Frr5---sn-nx5s7n76.googlevideo.com%2Finitplayback%3Fsource%3Dyoutube%26oeis%3D1%26c%3DWEB%26oad%3D3200%26ovd%3D3200%26oaad%3D11000%26oavd%3D11000%26ocs%3D700%26oewis%3D1%26oputc%3D1%26ofpcc%3D1%26msp%3D1%26odepv%3D1%26id%3D38654ad085c12212%26ip%3D38.93.247.21%26initcwndbps%3D11346250%26mt%3D1675748964%26oweuc%3D%26pxtags%3DCg4KAnR4EggyNDQ1MTI4OA%26rxtags%3DCg4KAnR4EggyNDQ1MTI4Ng%252CCg4KAnR4EggyNDQ1MTI4Nw%252CCg4KAnR4EggyNDQ1MTI4OA%252CCg4KAnR4EggyNDQ1MTI4OQ%22%7D%7D%7D%7D%7D',
  857. 'origin': 'https://www.youtube.com',
  858. 'pragma': 'no-cache',
  859. 'referer': f'https://www.youtube.com/watch?v={video_id}',
  860. 'sec-ch-ua': '"Not_A Brand";v="99", "Chromium";v="109", "Google Chrome";v="109.0.5414.87"',
  861. 'sec-ch-ua-arch': '"arm"',
  862. 'sec-ch-ua-bitness': '"64"',
  863. 'sec-ch-ua-full-version': '"109.0.1518.52"',
  864. 'sec-ch-ua-full-version-list': '"Not_A Brand";v="99.0.0.0", "Microsoft Edge";v="109.0.1518.52", "Chromium";v="109.0.5414.87"',
  865. 'sec-ch-ua-mobile': '?0',
  866. 'sec-ch-ua-model': '',
  867. 'sec-ch-ua-platform': '"macOS"',
  868. 'sec-ch-ua-platform-version': '"12.4.0"',
  869. 'sec-ch-ua-wow64': '?0',
  870. 'sec-fetch-dest': 'empty',
  871. 'sec-fetch-mode': 'same-origin',
  872. 'sec-fetch-site': 'same-origin',
  873. 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
  874. 'x-goog-visitor-id': 'CgtraDZfVnB4NXdIWSjkzoefBg%3D%3D',
  875. 'x-youtube-bootstrap-logged-in': 'false',
  876. 'x-youtube-client-name': '1',
  877. 'x-youtube-client-version': '2.20230201.01.00'
  878. }
  879. response = requests.post(url=url, headers=headers, data=payload)
  880. if response.status_code != 200:
  881. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.text}\n")
  882. elif 'streamingData' not in response.json():
  883. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  884. elif 'videoDetails' not in response.json():
  885. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  886. elif 'microformat' not in response.json():
  887. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  888. else:
  889. playerMicroformatRenderer = response.json()['microformat']['playerMicroformatRenderer']
  890. videoDetails = response.json()['videoDetails']
  891. # streamingData = response.json()['streamingData']
  892. # video_title
  893. if 'title' not in videoDetails:
  894. video_title = ''
  895. else:
  896. video_title = videoDetails['title'].replace("&", "").strip().replace("\n", "") \
  897. .replace("/", "").replace("\r", "").replace("#", "") \
  898. .replace(".", "。").replace("\\", "").replace("&NBSP", "")
  899. video_title = cls.filter_emoji(video_title)
  900. # if Translate.is_contains_chinese(video_title) is False:
  901. video_title = Translate.google_translate(video_title, machine) # 自动翻译标题为中文
  902. if 'lengthSeconds' not in videoDetails:
  903. duration = 0
  904. else:
  905. duration = int(videoDetails['lengthSeconds'])
  906. # play_cnt
  907. if 'viewCount' not in videoDetails:
  908. play_cnt = 0
  909. else:
  910. play_cnt = int(videoDetails['viewCount'])
  911. # publish_time
  912. if 'publishDate' not in playerMicroformatRenderer:
  913. publish_time = ''
  914. else:
  915. publish_time = playerMicroformatRenderer['publishDate']
  916. if publish_time == '':
  917. publish_time_stamp = 0
  918. elif ':' in publish_time:
  919. publish_time_stamp = int(time.mktime(time.strptime(publish_time, "%Y-%m-%d %H:%M:%S")))
  920. else:
  921. publish_time_stamp = int(time.mktime(time.strptime(publish_time, "%Y-%m-%d")))
  922. # user_name
  923. if 'author' not in videoDetails:
  924. user_name = ''
  925. else:
  926. user_name = videoDetails['author']
  927. # cover_url
  928. if 'thumbnail' not in videoDetails:
  929. cover_url = ''
  930. elif 'thumbnails' not in videoDetails['thumbnail']:
  931. cover_url = ''
  932. elif len(videoDetails['thumbnail']['thumbnails']) == 0:
  933. cover_url = ''
  934. elif 'url' not in videoDetails['thumbnail']['thumbnails'][-1]:
  935. cover_url = ''
  936. else:
  937. cover_url = videoDetails['thumbnail']['thumbnails'][-1]['url']
  938. # video_url
  939. # if 'formats' not in streamingData:
  940. # video_url = ''
  941. # elif len(streamingData['formats']) == 0:
  942. # video_url = ''
  943. # elif 'url' not in streamingData['formats'][-1]:
  944. # video_url = ''
  945. # else:
  946. # video_url = streamingData['formats'][-1]['url']
  947. video_url = f"https://www.youtube.com/watch?v={video_id}"
  948. Common.logger(log_type, crawler).info(f'video_title:{video_title}')
  949. Common.logger(log_type, crawler).info(f'video_id:{video_id}')
  950. Common.logger(log_type, crawler).info(f'play_cnt:{play_cnt}')
  951. Common.logger(log_type, crawler).info(f'publish_time:{publish_time}')
  952. Common.logger(log_type, crawler).info(f'user_name:{user_name}')
  953. Common.logger(log_type, crawler).info(f'cover_url:{cover_url}')
  954. Common.logger(log_type, crawler).info(f'video_url:{video_url}')
  955. video_dict = {
  956. 'video_title': video_title,
  957. 'video_id': video_id,
  958. 'duration': duration,
  959. 'play_cnt': play_cnt,
  960. 'publish_time': publish_time,
  961. 'publish_time_stamp': publish_time_stamp,
  962. 'user_name': user_name,
  963. 'out_uid': out_uid,
  964. 'cover_url': cover_url,
  965. 'video_url': video_url,
  966. }
  967. return video_dict
  968. except Exception as e:
  969. Common.logger(log_type, crawler).error(f"get_video_info异常:{e}\n")
  970. @classmethod
  971. def repeat_video(cls, log_type, crawler, video_id, env, machine):
  972. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  973. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  974. return len(repeat_video)
  975. @classmethod
  976. def download_publish(cls, log_type, crawler, video_dict, strategy, our_uid, env, oss_endpoint, machine):
  977. try:
  978. # sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_dict['video_id']}" """
  979. # repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  980. if video_dict['video_title'] == '' or video_dict['video_url'] == '':
  981. Common.logger(log_type, crawler).info('无效视频\n')
  982. elif video_dict['duration'] > 1200 or video_dict['duration'] < 60:
  983. Common.logger(log_type, crawler).info(f"时长:{video_dict['duration']}不满足规则\n")
  984. # elif repeat_video is not None and len(repeat_video) != 0:
  985. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env, machine) != 0:
  986. Common.logger(log_type, crawler).info('视频已下载\n')
  987. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, crawler, 'GVxlYk') for x in y]:
  988. Common.logger(log_type, crawler).info('视频已下载\n')
  989. else:
  990. # 下载视频
  991. Common.logger(log_type, crawler).info('开始下载视频...')
  992. # Common.download_method(log_type, crawler, 'video', video_dict['video_title'], video_dict['video_url'])
  993. Common.download_method(log_type, crawler, 'youtube_video', video_dict['video_title'], video_dict['video_url'])
  994. # ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  995. # video_width = int(ffmpeg_dict['width'])
  996. video_width = 1280
  997. # video_height = int(ffmpeg_dict['height'])
  998. video_height = 720
  999. duration = int(video_dict['duration'])
  1000. # video_size = int(ffmpeg_dict['size'])
  1001. Common.logger(log_type, crawler).info(f'video_width:{video_width}')
  1002. Common.logger(log_type, crawler).info(f'video_height:{video_height}')
  1003. Common.logger(log_type, crawler).info(f'duration:{duration}')
  1004. # Common.logger(log_type, crawler).info(f'video_size:{video_size}\n')
  1005. video_dict['video_width'] = video_width
  1006. video_dict['video_height'] = video_height
  1007. video_dict['duration'] = duration
  1008. video_dict['comment_cnt'] = 0
  1009. video_dict['like_cnt'] = 0
  1010. video_dict['share_cnt'] = 0
  1011. video_dict['avatar_url'] = video_dict['cover_url']
  1012. video_dict['session'] = f'youtube{int(time.time())}'
  1013. rule='1,2'
  1014. # if duration < 60 or duration > 600:
  1015. # # 删除视频文件夹
  1016. # shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}/")
  1017. # Common.logger(log_type, crawler).info(f"时长:{video_dict['duration']}不满足抓取规则,删除成功\n")
  1018. # return
  1019. if duration == 0 or duration is None:
  1020. # 删除视频文件夹
  1021. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}/")
  1022. Common.logger(log_type, crawler).info(f"视频下载出错,删除成功\n")
  1023. return
  1024. else:
  1025. # 下载封面
  1026. Common.download_method(log_type, crawler, 'cover', video_dict['video_title'], video_dict['cover_url'])
  1027. # 保存视频文本信息
  1028. Common.save_video_info(log_type, crawler, video_dict)
  1029. # 上传视频
  1030. Common.logger(log_type, crawler).info(f"开始上传视频")
  1031. if env == 'dev':
  1032. our_video_id = Publish.upload_and_publish(log_type, crawler, strategy, our_uid, env, oss_endpoint)
  1033. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  1034. else:
  1035. our_video_id = Publish.upload_and_publish(log_type, crawler, strategy, our_uid, env, oss_endpoint)
  1036. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  1037. Common.logger(log_type, crawler).info("视频上传完成")
  1038. # 视频信息保存至飞书
  1039. Feishu.insert_columns(log_type, crawler, "GVxlYk", "ROWS", 1, 2)
  1040. # 视频ID工作表,首行写入数据
  1041. upload_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
  1042. values = [[upload_time,
  1043. "定向榜",
  1044. video_dict['video_id'],
  1045. video_dict['video_title'],
  1046. our_video_link,
  1047. video_dict['play_cnt'],
  1048. video_dict['duration'],
  1049. f'{video_width}*{video_height}',
  1050. video_dict['publish_time'],
  1051. video_dict['user_name'],
  1052. video_dict['cover_url'],
  1053. video_dict['video_url']
  1054. ]]
  1055. time.sleep(1)
  1056. Feishu.update_values(log_type, crawler, "GVxlYk", "F2:Z2", values)
  1057. Common.logger(log_type, crawler).info('视频信息写入定向_已下载表成功\n')
  1058. # 视频信息保存数据库
  1059. sql = f""" insert into crawler_video(video_id,
  1060. user_id,
  1061. out_user_id,
  1062. platform,
  1063. strategy,
  1064. out_video_id,
  1065. video_title,
  1066. cover_url,
  1067. video_url,
  1068. duration,
  1069. publish_time,
  1070. play_cnt,
  1071. crawler_rule,
  1072. width,
  1073. height)
  1074. values({our_video_id},
  1075. "{our_uid}",
  1076. "{video_dict['out_uid']}",
  1077. "{cls.platform}",
  1078. "定向爬虫策略",
  1079. "{video_dict['video_id']}",
  1080. "{video_dict['video_title']}",
  1081. "{video_dict['cover_url']}",
  1082. "{video_dict['video_url']}",
  1083. {int(duration)},
  1084. "{video_dict['publish_time']}",
  1085. {int(video_dict['play_cnt'])},
  1086. "{rule}",
  1087. {int(video_width)},
  1088. {int(video_height)}) """
  1089. MysqlHelper.update_values(log_type, crawler, sql, env, machine)
  1090. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  1091. except Exception as e:
  1092. Common.logger(log_type, crawler).info(f"download_publish异常:{e}\n")
  1093. @classmethod
  1094. def get_follow_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine):
  1095. try:
  1096. user_list = cls.get_user_from_feishu(log_type, crawler, 'c467d7', env, machine)
  1097. if len(user_list) == 0:
  1098. Common.logger(log_type, crawler).warning('用户列表为空\n')
  1099. else:
  1100. for user_dict in user_list:
  1101. out_uid = user_dict['out_user_id']
  1102. user_name = user_dict['out_user_name']
  1103. browse_id = user_dict['out_browse_id']
  1104. our_uid = user_dict['our_user_id']
  1105. Common.logger(log_type, crawler).info(f'获取 {user_name} 主页视频\n')
  1106. cls.get_videos(log_type, crawler, strategy, oss_endpoint, env, browse_id, out_uid, our_uid, machine)
  1107. Common.logger(log_type, crawler).info('休眠 10 秒')
  1108. time.sleep(10)
  1109. cls.continuation = ''
  1110. except Exception as e:
  1111. Common.logger(log_type, crawler).error(f"get_follow_videos异常:{e}\n")
  1112. if __name__ == "__main__":
  1113. # print(Follow.get_browse_id('follow', 'youtube', '@chinatravel5971', "local"))
  1114. # print(Follow.get_user_from_feishu('follow', 'youtube', 'c467d7', 'dev', 'local'))
  1115. # Follow.get_out_user_info('follow', 'youtube', 'UC08jgxf119fzynp2uHCvZIg', '@weitravel')
  1116. # Follow.get_video_info('follow', 'youtube', 'OGVK0IXBIhI')
  1117. # Follow.get_follow_videos('follow', 'youtube', 'youtube_follow', 'out', 'dev', 'local')
  1118. # print(Follow.filter_emoji("姐妹倆一唱一和,完美配合,終於把大慶降服了😅😅#萌娃搞笑日常"))
  1119. # Follow.repeat_video('follow', 'youtube', 4, "dev", "local")
  1120. pass