youtube_follow.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  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. else:
  331. pass
  332. # 站外用户总播放量
  333. if 'viewCountText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  334. out_play_cnt = 0
  335. elif 'simpleText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['viewCountText']:
  336. out_play_cnt = 0
  337. else:
  338. out_play_cnt = int(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['viewCountText']['simpleText'].split('次')[0].replace(',', ''))
  339. # 站外用户注册时间
  340. if 'joinedDateText' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']:
  341. out_create_time = ''
  342. elif 'runs' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']:
  343. out_create_time = ''
  344. elif len(tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs']) == 0:
  345. out_create_time = ''
  346. elif 'text' not in tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs'][0]:
  347. out_create_time = ''
  348. else:
  349. out_create_time = tabs[i]['tabRenderer']['content']['sectionListRenderer']['contents'][0]['itemSectionRenderer']['contents'][0]['channelAboutFullMetadataRenderer']['joinedDateText']['runs'][0]['text'].replace('年', '-').replace('月', '-').replace('日', '')
  350. out_user_dict = {
  351. 'out_user_name': out_user_name,
  352. 'out_avatar_url': out_avatar_url,
  353. 'out_fans': out_fans,
  354. 'out_play_cnt': out_play_cnt,
  355. 'out_create_time': out_create_time,
  356. }
  357. # print(out_user_dict)
  358. return out_user_dict
  359. except Exception as e:
  360. Common.logger(log_type, crawler).error(f'get_out_user_info异常:{e}\n')
  361. @classmethod
  362. def get_user_from_feishu(cls, log_type, crawler, sheetid, env, machine):
  363. """
  364. 补全飞书用户表信息,并返回
  365. :param log_type: 日志
  366. :param crawler: 哪款爬虫
  367. :param sheetid: 飞书表
  368. :param env: 正式环境:prod,测试环境:dev
  369. :param machine: 部署机器,阿里云填写 aliyun,aliyun_hk ,线下分别填写 macpro,macair,local
  370. :return: user_list
  371. """
  372. try:
  373. user_sheet = Feishu.get_values_batch(log_type, crawler, sheetid)
  374. user_list = []
  375. for i in range(1, len(user_sheet)):
  376. out_uid = user_sheet[i][2]
  377. user_name = user_sheet[i][3]
  378. browse_id = user_sheet[i][5]
  379. our_uid = user_sheet[i][6]
  380. Common.logger(log_type, crawler).info(f"正在更新 {user_name} 用户信息\n")
  381. # 获取站外browse_id,并写入飞书
  382. if browse_id is None:
  383. browse_id = cls.get_browse_id(log_type, crawler, out_uid, machine)
  384. if browse_id is None:
  385. Common.logger(log_type, crawler).warning('browse_id is None !')
  386. else:
  387. Feishu.update_values(log_type, crawler, sheetid, f'F{i+1}:F{i+1}', [[browse_id]])
  388. Common.logger(log_type, crawler).info(f'browse_id写入成功:{browse_id}')
  389. # 站内 UID 为空,且数据库中(youtube+out_user_id)返回数量 == 0,则创建新的站内账号
  390. if our_uid is None:
  391. sql = f""" select * from crawler_user where platform="{cls.platform}" and out_user_id="{out_uid}" """
  392. our_user_info = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  393. # 数据库中(youtube + out_user_id)返回数量 == 0,则创建站内账号UID,并写入定向账号飞书表。并结合站外用户信息,一并写入爬虫账号数据库
  394. if our_user_info is None or len(our_user_info) == 0:
  395. # 获取站外账号信息,写入数据库
  396. out_user_dict = cls.get_out_user_info(log_type, crawler, browse_id, out_uid)
  397. out_avatar_url = out_user_dict['out_avatar_url']
  398. out_create_time = out_user_dict['out_create_time']
  399. out_play_cnt = out_user_dict['out_play_cnt']
  400. out_fans = out_user_dict['out_fans']
  401. tag = 'youtube爬虫,定向爬虫策略'
  402. # 创建站内账号
  403. create_user_dict = {
  404. 'nickName': user_name,
  405. 'avatarUrl': out_avatar_url,
  406. 'tagName': tag,
  407. }
  408. our_uid = Users.create_user(log_type, crawler, create_user_dict, env)
  409. Common.logger(log_type, crawler).info(f'新创建的站内UID:{our_uid}')
  410. if env == 'prod':
  411. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  412. else:
  413. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  414. Common.logger(log_type, crawler).info(f'站内用户主页链接:{our_user_link}')
  415. Feishu.update_values(log_type, crawler, sheetid, f'G{i + 1}:H{i + 1}', [[our_uid, our_user_link]])
  416. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!')
  417. Common.logger(log_type, crawler).info(f'sql:{sql}')
  418. sql = f""" insert into crawler_user(user_id,
  419. out_user_id,
  420. out_user_name,
  421. out_avatar_url,
  422. out_create_time,
  423. out_play_cnt,
  424. out_fans,
  425. platform,
  426. tag)
  427. values({our_uid},
  428. "{out_uid}",
  429. "{user_name}",
  430. "{out_avatar_url}",
  431. "{out_create_time}",
  432. {out_play_cnt},
  433. {out_fans},
  434. "{cls.platform}",
  435. "{tag}") """
  436. MysqlHelper.update_values(log_type, crawler, sql, env, machine)
  437. Common.logger(log_type, crawler).info('用户信息插入数据库成功!\n')
  438. # 数据库中(youtube + out_user_id)返回数量 != 0,则直接把数据库中的站内 UID 写入飞书
  439. else:
  440. our_uid = our_user_info[0][1]
  441. if 'env' == 'prod':
  442. our_user_link = f'https://admin.piaoquantv.com/ums/user/{our_uid}/post'
  443. else:
  444. our_user_link = f'https://testadmin.piaoquantv.com/ums/user/{our_uid}/post'
  445. Common.logger(log_type, crawler).info(f'站内用户主页链接:{our_user_link}')
  446. Feishu.update_values(log_type, crawler, sheetid, f'G{i+1}:H{i+1}', [[our_uid, our_user_link]])
  447. Common.logger(log_type, crawler).info(f'站内用户信息写入飞书成功!\n')
  448. user_dict = {
  449. 'out_user_id': out_uid,
  450. 'out_user_name': user_name,
  451. 'out_browse_id': browse_id,
  452. 'our_user_id': our_uid,
  453. }
  454. user_list.append(user_dict)
  455. return user_list
  456. except Exception as e:
  457. Common.logger(log_type, crawler).error(f"get_user_from_feishu异常:{e}\n")
  458. @classmethod
  459. def get_feeds(cls, log_type, crawler, browse_id, out_uid):
  460. """
  461. 获取个人主页视频列表
  462. :param log_type: 日志
  463. :param crawler: 哪款爬虫
  464. :param browse_id: 每个用户主页的请求参数中唯一值
  465. :param out_uid: 站外用户UID
  466. :return: video_list
  467. """
  468. url = "https://www.youtube.com/youtubei/v1/browse?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
  469. payload = json.dumps({
  470. "context": {
  471. "client": {
  472. "hl": "zh-CN",
  473. "gl": "US",
  474. "remoteHost": "38.93.247.21",
  475. "deviceMake": "Apple",
  476. "deviceModel": "",
  477. "visitorData": "CgtraDZfVnB4NXdIWSi6mIOfBg%3D%3D",
  478. "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)",
  479. "clientName": "WEB",
  480. "clientVersion": "2.20230201.01.00",
  481. "osName": "Macintosh",
  482. "osVersion": "10_15_7",
  483. "originalUrl": f"https://www.youtube.com/{out_uid}/videos",
  484. "platform": "DESKTOP",
  485. "clientFormFactor": "UNKNOWN_FORM_FACTOR",
  486. "configInfo": {
  487. "appInstallData": "CLqYg58GEInorgUQuIuuBRCU-K4FENfkrgUQuNSuBRC2nP4SEPuj_hIQ5_euBRCy9a4FEKLsrgUQt-CuBRDi1K4FEILdrgUQh92uBRDM364FEP7urgUQzPWuBRDZ6a4FEOSg_hIQo_muBRDvo_4SEMnJrgUQlqf-EhCR-PwS"
  488. },
  489. "timeZone": "Asia/Shanghai",
  490. "browserName": "Chrome",
  491. "browserVersion": "109.0.0.0",
  492. "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",
  493. "deviceExperimentId": "ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09ELqYg58GGOmU7Z4G",
  494. "screenWidthPoints": 944,
  495. "screenHeightPoints": 969,
  496. "screenPixelDensity": 1,
  497. "screenDensityFloat": 1,
  498. "utcOffsetMinutes": 480,
  499. "userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT",
  500. "memoryTotalKbytes": "8000000",
  501. "mainAppWebInfo": {
  502. "graftUrl": f"/{out_uid}/videos",
  503. "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_CAN_BE_INSTALLED",
  504. "webDisplayMode": "WEB_DISPLAY_MODE_FULLSCREEN",
  505. "isWebNativeShareAvailable": True
  506. }
  507. },
  508. "user": {
  509. "lockedSafetyMode": False
  510. },
  511. "request": {
  512. "useSsl": True,
  513. "internalExperimentFlags": [],
  514. "consistencyTokenJars": []
  515. },
  516. "clickTracking": {
  517. "clickTrackingParams": "CBcQ8JMBGAYiEwiNhIXX9IL9AhUFSUwIHWnnDks="
  518. },
  519. "adSignalsInfo": {
  520. "params": [
  521. {
  522. "key": "dt",
  523. "value": "1675676731048"
  524. },
  525. {
  526. "key": "flash",
  527. "value": "0"
  528. },
  529. {
  530. "key": "frm",
  531. "value": "0"
  532. },
  533. {
  534. "key": "u_tz",
  535. "value": "480"
  536. },
  537. {
  538. "key": "u_his",
  539. "value": "4"
  540. },
  541. {
  542. "key": "u_h",
  543. "value": "1080"
  544. },
  545. {
  546. "key": "u_w",
  547. "value": "1920"
  548. },
  549. {
  550. "key": "u_ah",
  551. "value": "1080"
  552. },
  553. {
  554. "key": "u_aw",
  555. "value": "1920"
  556. },
  557. {
  558. "key": "u_cd",
  559. "value": "24"
  560. },
  561. {
  562. "key": "bc",
  563. "value": "31"
  564. },
  565. {
  566. "key": "bih",
  567. "value": "969"
  568. },
  569. {
  570. "key": "biw",
  571. "value": "944"
  572. },
  573. {
  574. "key": "brdim",
  575. "value": "-269,-1080,-269,-1080,1920,-1080,1920,1080,944,969"
  576. },
  577. {
  578. "key": "vis",
  579. "value": "1"
  580. },
  581. {
  582. "key": "wgl",
  583. "value": "true"
  584. },
  585. {
  586. "key": "ca_type",
  587. "value": "image"
  588. }
  589. ],
  590. "bid": "ANyPxKpfiaAf-DBzNeKLgkceMEA9UIeCWFRTRm4AQMCuejhI3PGwDB1jizQIX60YcEYtt_CX7tZWAbYerQ-rWLvV7y_KCLkBww"
  591. }
  592. },
  593. "browseId": browse_id,
  594. "params": "EgZ2aWRlb3PyBgQKAjoA",
  595. "continuation": cls.continuation
  596. })
  597. headers = {
  598. 'authority': 'www.youtube.com',
  599. 'accept': '*/*',
  600. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  601. 'cache-control': 'no-cache',
  602. 'content-type': 'application/json',
  603. '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',
  604. 'origin': 'https://www.youtube.com',
  605. 'pragma': 'no-cache',
  606. 'referer': f'https://www.youtube.com/{out_uid}/featured',
  607. 'sec-ch-ua': '"Not_A Brand";v="99", "Chromium";v="109", "Google Chrome";v="109.0.5414.87"',
  608. 'sec-ch-ua-arch': '"arm"',
  609. 'sec-ch-ua-bitness': '"64"',
  610. 'sec-ch-ua-full-version': '"109.0.1518.52"',
  611. '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"',
  612. 'sec-ch-ua-mobile': '?0',
  613. 'sec-ch-ua-model': '',
  614. 'sec-ch-ua-platform': '"macOS"',
  615. 'sec-ch-ua-platform-version': '"12.4.0"',
  616. 'sec-ch-ua-wow64': '?0',
  617. 'sec-fetch-dest': 'empty',
  618. 'sec-fetch-mode': 'same-origin',
  619. 'sec-fetch-site': 'same-origin',
  620. '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',
  621. 'x-goog-visitor-id': 'CgtraDZfVnB4NXdIWSi6mIOfBg%3D%3D',
  622. 'x-youtube-bootstrap-logged-in': 'false',
  623. 'x-youtube-client-name': '1',
  624. 'x-youtube-client-version': '2.20230201.01.00'
  625. }
  626. try:
  627. response = requests.post(url=url, headers=headers, data=payload)
  628. # Common.logger(log_type, crawler).info(f"get_feeds_response:{response.json()}\n")
  629. cls.continuation = response.json()['trackingParams']
  630. if response.status_code != 200:
  631. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.text}\n')
  632. elif 'continuationContents' not in response.text and 'onResponseReceivedActions' not in response.text:
  633. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.text}\n')
  634. elif 'continuationContents' in response.json():
  635. # Common.logger(log_type, crawler).info("'continuationContents' in response.json()\n")
  636. if 'richGridContinuation' not in response.json()['continuationContents']:
  637. # Common.logger(log_type, crawler).warning(f"'richGridContinuation' not in response.json()['continuationContents']\n")
  638. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["continuationContents"]}\n')
  639. elif 'contents' not in response.json()['continuationContents']['richGridContinuation']:
  640. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["continuationContents"]["richGridContinuation"]}\n')
  641. elif 'contents' in response.json()["continuationContents"]["richGridContinuation"]:
  642. feeds = response.json()["continuationContents"]["richGridContinuation"]['contents']
  643. return feeds
  644. elif 'onResponseReceivedActions' in response.json():
  645. Common.logger(log_type, crawler).info("'onResponseReceivedActions' in response.json()\n")
  646. if len(response.json()['onResponseReceivedActions']) == 0:
  647. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"]}\n')
  648. elif 'appendContinuationItemsAction' not in response.json()['onResponseReceivedActions'][0]:
  649. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]}\n')
  650. elif 'continuationItems' not in response.json()['onResponseReceivedActions'][0]['appendContinuationItemsAction']:
  651. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]}\n')
  652. elif len(response.json()['onResponseReceivedActions'][0]['appendContinuationItemsAction']['continuationItems']) == 0:
  653. Common.logger(log_type, crawler).warning(f'get_feeds_response:{response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]["continuationItems"]}\n')
  654. else:
  655. feeds = response.json()["onResponseReceivedActions"][0]["appendContinuationItemsAction"]["continuationItems"]
  656. return feeds
  657. else:
  658. Common.logger(log_type, crawler).info('feeds is None\n')
  659. except Exception as e:
  660. Common.logger(log_type, crawler).error(f'get_feeds异常:{e}\n')
  661. @classmethod
  662. def get_videos(cls, log_type, crawler, strategy, oss_endpoint, env, browse_id, out_uid, our_uid, machine):
  663. try:
  664. while True:
  665. feeds = cls.get_feeds(log_type, crawler, browse_id, out_uid)
  666. for i in range(len(feeds)):
  667. if 'richItemRenderer' not in feeds[i]:
  668. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]}\n')
  669. return
  670. elif 'content' not in feeds[i]['richItemRenderer']:
  671. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]}\n')
  672. return
  673. elif 'videoRenderer' not in feeds[i]['richItemRenderer']['content']:
  674. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]["content"]}\n')
  675. return
  676. elif 'videoId' not in feeds[i]["richItemRenderer"]["content"]['videoRenderer']:
  677. Common.logger(log_type, crawler).warning(f'feeds:{feeds[i]["richItemRenderer"]["content"]["videoRenderer"]}\n')
  678. return
  679. else:
  680. video_id = feeds[i]["richItemRenderer"]["content"]['videoRenderer']['videoId']
  681. video_dict = cls.get_video_info(log_type, crawler, out_uid, video_id, machine)
  682. # 发布时间<=30天
  683. publish_time = int(time.mktime(time.strptime(video_dict['publish_time'], "%Y-%m-%d")))
  684. if int(time.time()) - publish_time <= 3600*24*30:
  685. cls.download_publish(log_type, crawler, video_dict, strategy, our_uid, env, oss_endpoint, machine)
  686. else:
  687. Common.logger(log_type, crawler).info('发布时间超过30天\n')
  688. return
  689. except Exception as e:
  690. Common.logger(log_type, crawler).error(f"get_videos异常:{e}\n")
  691. @classmethod
  692. def filter_emoji(cls, title):
  693. # 过滤表情
  694. try:
  695. co = re.compile(u'[\U00010000-\U0010ffff]')
  696. except re.error:
  697. co = re.compile(u'[\uD800-\uDBFF][\uDC00-\uDFFF]')
  698. return co.sub("", title)
  699. @classmethod
  700. def get_video_info(cls, log_type, crawler, out_uid, video_id, machine):
  701. try:
  702. url = "https://www.youtube.com/youtubei/v1/player?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false"
  703. payload = json.dumps({
  704. "context": {
  705. "client": {
  706. "hl": "zh-CN",
  707. "gl": "US",
  708. "remoteHost": "38.93.247.21",
  709. "deviceMake": "Apple",
  710. "deviceModel": "",
  711. "visitorData": "CgtraDZfVnB4NXdIWSjkzoefBg%3D%3D",
  712. "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)",
  713. "clientName": "WEB",
  714. "clientVersion": "2.20230201.01.00",
  715. "osName": "Macintosh",
  716. "osVersion": "10_15_7",
  717. "originalUrl": f"https://www.youtube.com/watch?v={video_id}",
  718. "platform": "DESKTOP",
  719. "clientFormFactor": "UNKNOWN_FORM_FACTOR",
  720. "configInfo": {
  721. "appInstallData": "COTOh58GEPuj_hIQ1-SuBRC4i64FEMzfrgUQgt2uBRCi7K4FEOLUrgUQzPWuBRCKgK8FEOSg_hIQtpz-EhDa6a4FEP7urgUQieiuBRDn964FELjUrgUQlPiuBRCH3a4FELfgrgUQ76P-EhDJya4FEJan_hIQkfj8Eg%3D%3D"
  722. },
  723. "timeZone": "Asia/Shanghai",
  724. "browserName": "Chrome",
  725. "browserVersion": "109.0.0.0",
  726. "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",
  727. "deviceExperimentId": "ChxOekU1TlRReU5qWTBOVFExTVRRNU5qRTBOdz09EOTOh58GGOmU7Z4G",
  728. "screenWidthPoints": 1037,
  729. "screenHeightPoints": 969,
  730. "screenPixelDensity": 1,
  731. "screenDensityFloat": 1,
  732. "utcOffsetMinutes": 480,
  733. "userInterfaceTheme": "USER_INTERFACE_THEME_LIGHT",
  734. "memoryTotalKbytes": "8000000",
  735. "clientScreen": "WATCH",
  736. "mainAppWebInfo": {
  737. "graftUrl": f"/watch?v={video_id}",
  738. "pwaInstallabilityStatus": "PWA_INSTALLABILITY_STATUS_CAN_BE_INSTALLED",
  739. "webDisplayMode": "WEB_DISPLAY_MODE_FULLSCREEN",
  740. "isWebNativeShareAvailable": True
  741. }
  742. },
  743. "user": {
  744. "lockedSafetyMode": False
  745. },
  746. "request": {
  747. "useSsl": True,
  748. "internalExperimentFlags": [],
  749. "consistencyTokenJars": []
  750. },
  751. "clickTracking": {
  752. "clickTrackingParams": "CIwBEKQwGAYiEwipncqx3IL9AhXs4cQKHbKZDO4yB3JlbGF0ZWRInsS1qbGFtIlUmgEFCAEQ-B0="
  753. },
  754. "adSignalsInfo": {
  755. "params": [
  756. {
  757. "key": "dt",
  758. "value": "1675749222611"
  759. },
  760. {
  761. "key": "flash",
  762. "value": "0"
  763. },
  764. {
  765. "key": "frm",
  766. "value": "0"
  767. },
  768. {
  769. "key": "u_tz",
  770. "value": "480"
  771. },
  772. {
  773. "key": "u_his",
  774. "value": "3"
  775. },
  776. {
  777. "key": "u_h",
  778. "value": "1080"
  779. },
  780. {
  781. "key": "u_w",
  782. "value": "1920"
  783. },
  784. {
  785. "key": "u_ah",
  786. "value": "1080"
  787. },
  788. {
  789. "key": "u_aw",
  790. "value": "1920"
  791. },
  792. {
  793. "key": "u_cd",
  794. "value": "24"
  795. },
  796. {
  797. "key": "bc",
  798. "value": "31"
  799. },
  800. {
  801. "key": "bih",
  802. "value": "969"
  803. },
  804. {
  805. "key": "biw",
  806. "value": "1037"
  807. },
  808. {
  809. "key": "brdim",
  810. "value": "-269,-1080,-269,-1080,1920,-1080,1920,1080,1037,969"
  811. },
  812. {
  813. "key": "vis",
  814. "value": "1"
  815. },
  816. {
  817. "key": "wgl",
  818. "value": "true"
  819. },
  820. {
  821. "key": "ca_type",
  822. "value": "image"
  823. }
  824. ],
  825. "bid": "ANyPxKop8SijebwUCq4ZfKbJwlSjVQa_RTdS6c6a6WPYpCKnxpWCJ33B1SzRuSXjSfH9O2MhURebAs0CngRg6B4nOjBpeJDKgA"
  826. }
  827. },
  828. "videoId": str(video_id),
  829. "playbackContext": {
  830. "contentPlaybackContext": {
  831. "currentUrl": f"/watch?v={video_id}",
  832. "vis": 0,
  833. "splay": False,
  834. "autoCaptionsDefaultOn": False,
  835. "autonavState": "STATE_NONE",
  836. "html5Preference": "HTML5_PREF_WANTS",
  837. "signatureTimestamp": 19394,
  838. "referer": f"https://www.youtube.com/watch?v={video_id}",
  839. "lactMilliseconds": "-1",
  840. "watchAmbientModeContext": {
  841. "watchAmbientModeEnabled": True
  842. }
  843. }
  844. },
  845. "racyCheckOk": False,
  846. "contentCheckOk": False
  847. })
  848. headers = {
  849. 'authority': 'www.youtube.com',
  850. 'accept': '*/*',
  851. 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
  852. 'cache-control': 'no-cache',
  853. 'content-type': 'application/json',
  854. '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',
  855. 'origin': 'https://www.youtube.com',
  856. 'pragma': 'no-cache',
  857. 'referer': f'https://www.youtube.com/watch?v={video_id}',
  858. 'sec-ch-ua': '"Not_A Brand";v="99", "Chromium";v="109", "Google Chrome";v="109.0.5414.87"',
  859. 'sec-ch-ua-arch': '"arm"',
  860. 'sec-ch-ua-bitness': '"64"',
  861. 'sec-ch-ua-full-version': '"109.0.1518.52"',
  862. '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"',
  863. 'sec-ch-ua-mobile': '?0',
  864. 'sec-ch-ua-model': '',
  865. 'sec-ch-ua-platform': '"macOS"',
  866. 'sec-ch-ua-platform-version': '"12.4.0"',
  867. 'sec-ch-ua-wow64': '?0',
  868. 'sec-fetch-dest': 'empty',
  869. 'sec-fetch-mode': 'same-origin',
  870. 'sec-fetch-site': 'same-origin',
  871. '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',
  872. 'x-goog-visitor-id': 'CgtraDZfVnB4NXdIWSjkzoefBg%3D%3D',
  873. 'x-youtube-bootstrap-logged-in': 'false',
  874. 'x-youtube-client-name': '1',
  875. 'x-youtube-client-version': '2.20230201.01.00'
  876. }
  877. response = requests.post(url=url, headers=headers, data=payload)
  878. if response.status_code != 200:
  879. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.text}\n")
  880. elif 'streamingData' not in response.json():
  881. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  882. elif 'videoDetails' not in response.json():
  883. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  884. elif 'microformat' not in response.json():
  885. Common.logger(log_type, crawler).warning(f"get_video_info_response:{response.json()}\n")
  886. else:
  887. playerMicroformatRenderer = response.json()['microformat']['playerMicroformatRenderer']
  888. videoDetails = response.json()['videoDetails']
  889. # streamingData = response.json()['streamingData']
  890. # video_title
  891. if 'title' not in videoDetails:
  892. video_title = ''
  893. else:
  894. video_title = videoDetails['title']
  895. video_title = cls.filter_emoji(video_title)
  896. # if Translate.is_contains_chinese(video_title) is False:
  897. video_title = Translate.google_translate(video_title, machine) # 自动翻译标题为中文
  898. if 'lengthSeconds' not in videoDetails:
  899. duration = 0
  900. else:
  901. duration = int(videoDetails['lengthSeconds'])
  902. # play_cnt
  903. if 'viewCount' not in videoDetails:
  904. play_cnt = 0
  905. else:
  906. play_cnt = int(videoDetails['viewCount'])
  907. # publish_time
  908. if 'publishDate' not in playerMicroformatRenderer:
  909. publish_time = ''
  910. else:
  911. publish_time = playerMicroformatRenderer['publishDate']
  912. if publish_time == '':
  913. publish_time_stamp = 0
  914. elif ':' in publish_time:
  915. publish_time_stamp = int(time.mktime(time.strptime(publish_time, "%Y-%m-%d %H:%M:%S")))
  916. else:
  917. publish_time_stamp = int(time.mktime(time.strptime(publish_time, "%Y-%m-%d")))
  918. # user_name
  919. if 'author' not in videoDetails:
  920. user_name = ''
  921. else:
  922. user_name = videoDetails['author']
  923. # cover_url
  924. if 'thumbnail' not in videoDetails:
  925. cover_url = ''
  926. elif 'thumbnails' not in videoDetails['thumbnail']:
  927. cover_url = ''
  928. elif len(videoDetails['thumbnail']['thumbnails']) == 0:
  929. cover_url = ''
  930. elif 'url' not in videoDetails['thumbnail']['thumbnails'][-1]:
  931. cover_url = ''
  932. else:
  933. cover_url = videoDetails['thumbnail']['thumbnails'][-1]['url']
  934. # video_url
  935. # if 'formats' not in streamingData:
  936. # video_url = ''
  937. # elif len(streamingData['formats']) == 0:
  938. # video_url = ''
  939. # elif 'url' not in streamingData['formats'][-1]:
  940. # video_url = ''
  941. # else:
  942. # video_url = streamingData['formats'][-1]['url']
  943. video_url = f"https://www.youtube.com/watch?v={video_id}"
  944. Common.logger(log_type, crawler).info(f'video_title:{video_title}')
  945. Common.logger(log_type, crawler).info(f'video_id:{video_id}')
  946. Common.logger(log_type, crawler).info(f'play_cnt:{play_cnt}')
  947. Common.logger(log_type, crawler).info(f'publish_time:{publish_time}')
  948. Common.logger(log_type, crawler).info(f'user_name:{user_name}')
  949. Common.logger(log_type, crawler).info(f'cover_url:{cover_url}')
  950. Common.logger(log_type, crawler).info(f'video_url:{video_url}')
  951. video_dict = {
  952. 'video_title': video_title,
  953. 'video_id': video_id,
  954. 'duration': duration,
  955. 'play_cnt': play_cnt,
  956. 'publish_time': publish_time,
  957. 'publish_time_stamp': publish_time_stamp,
  958. 'user_name': user_name,
  959. 'out_uid': out_uid,
  960. 'cover_url': cover_url,
  961. 'video_url': video_url,
  962. }
  963. return video_dict
  964. except Exception as e:
  965. Common.logger(log_type, crawler).error(f"get_video_info异常:{e}\n")
  966. @classmethod
  967. def repeat_video(cls, log_type, crawler, video_id, env, machine):
  968. sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_id}"; """
  969. repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  970. return len(repeat_video)
  971. @classmethod
  972. def download_publish(cls, log_type, crawler, video_dict, strategy, our_uid, env, oss_endpoint, machine):
  973. try:
  974. # sql = f""" select * from crawler_video where platform="{cls.platform}" and out_video_id="{video_dict['video_id']}" """
  975. # repeat_video = MysqlHelper.get_values(log_type, crawler, sql, env, machine)
  976. if video_dict['video_title'] == '' or video_dict['video_url'] == '':
  977. Common.logger(log_type, crawler).info('无效视频\n')
  978. elif video_dict['duration'] > 600 or video_dict['duration'] < 60:
  979. Common.logger(log_type, crawler).info(f"时长:{video_dict['duration']}不满足规则\n")
  980. # elif repeat_video is not None and len(repeat_video) != 0:
  981. elif cls.repeat_video(log_type, crawler, video_dict['video_id'], env, machine) != 0:
  982. Common.logger(log_type, crawler).info('视频已下载\n')
  983. elif video_dict['video_id'] in [x for y in Feishu.get_values_batch(log_type, crawler, 'GVxlYk') for x in y]:
  984. Common.logger(log_type, crawler).info('视频已下载\n')
  985. else:
  986. # 下载视频
  987. Common.logger(log_type, crawler).info('开始下载视频...')
  988. # Common.download_method(log_type, crawler, 'video', video_dict['video_title'], video_dict['video_url'])
  989. Common.download_method(log_type, crawler, 'youtube_video', video_dict['video_title'], video_dict['video_url'])
  990. ffmpeg_dict = Common.ffmpeg(log_type, crawler, f"./{crawler}/videos/{video_dict['video_title']}/video.mp4")
  991. video_width = int(ffmpeg_dict['width'])
  992. video_height = int(ffmpeg_dict['height'])
  993. duration = int(ffmpeg_dict['duration'])
  994. video_size = int(ffmpeg_dict['size'])
  995. Common.logger(log_type, crawler).info(f'video_width:{video_width}')
  996. Common.logger(log_type, crawler).info(f'video_height:{video_height}')
  997. Common.logger(log_type, crawler).info(f'duration:{duration}')
  998. Common.logger(log_type, crawler).info(f'video_size:{video_size}\n')
  999. video_dict['video_width'] = video_width
  1000. video_dict['video_height'] = video_height
  1001. video_dict['duration'] = duration
  1002. video_dict['comment_cnt'] = 0
  1003. video_dict['like_cnt'] = 0
  1004. video_dict['share_cnt'] = 0
  1005. video_dict['avatar_url'] = video_dict['cover_url']
  1006. video_dict['session'] = f'youtube{int(time.time())}'
  1007. rule='1,2'
  1008. # if duration < 60 or duration > 600:
  1009. # # 删除视频文件夹
  1010. # shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}/")
  1011. # Common.logger(log_type, crawler).info(f"时长:{video_dict['duration']}不满足抓取规则,删除成功\n")
  1012. # return
  1013. if video_size == 0 or duration == 0 or video_size is None or duration is None:
  1014. # 删除视频文件夹
  1015. shutil.rmtree(f"./{crawler}/videos/{video_dict['video_title']}/")
  1016. Common.logger(log_type, crawler).info(f"视频下载出错,删除成功\n")
  1017. return
  1018. else:
  1019. # 下载封面
  1020. Common.download_method(log_type, crawler, 'cover', video_dict['video_title'], video_dict['cover_url'])
  1021. # 保存视频文本信息
  1022. Common.save_video_info(log_type, crawler, video_dict)
  1023. # 上传视频
  1024. Common.logger(log_type, crawler).info(f"开始上传视频")
  1025. if env == 'dev':
  1026. our_video_id = Publish.upload_and_publish(log_type, crawler, strategy, our_uid, env, oss_endpoint)
  1027. our_video_link = f"https://testadmin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  1028. else:
  1029. our_video_id = Publish.upload_and_publish(log_type, crawler, strategy, our_uid, env, oss_endpoint)
  1030. our_video_link = f"https://admin.piaoquantv.com/cms/post-detail/{our_video_id}/info"
  1031. Common.logger(log_type, crawler).info("视频上传完成")
  1032. # 视频信息保存至飞书
  1033. Feishu.insert_columns(log_type, crawler, "GVxlYk", "ROWS", 1, 2)
  1034. # 视频ID工作表,首行写入数据
  1035. upload_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time())))
  1036. values = [[upload_time,
  1037. "定向榜",
  1038. video_dict['video_id'],
  1039. video_dict['video_title'],
  1040. our_video_link,
  1041. video_dict['play_cnt'],
  1042. video_dict['duration'],
  1043. f'{video_width}*{video_height}',
  1044. video_dict['publish_time'],
  1045. video_dict['user_name'],
  1046. video_dict['cover_url'],
  1047. video_dict['video_url']
  1048. ]]
  1049. time.sleep(1)
  1050. Feishu.update_values(log_type, crawler, "GVxlYk", "F2:Z2", values)
  1051. Common.logger(log_type, crawler).info('视频信息写入定向_已下载表成功\n')
  1052. # 视频信息保存数据库
  1053. sql = f""" insert into crawler_video(video_id,
  1054. user_id,
  1055. out_user_id,
  1056. platform,
  1057. strategy,
  1058. out_video_id,
  1059. video_title,
  1060. cover_url,
  1061. video_url,
  1062. duration,
  1063. publish_time,
  1064. play_cnt,
  1065. crawler_rule,
  1066. width,
  1067. height)
  1068. values({our_video_id},
  1069. "{our_uid}",
  1070. "{video_dict['out_uid']}",
  1071. "{cls.platform}",
  1072. "定向爬虫策略",
  1073. "{video_dict['video_id']}",
  1074. "{video_dict['video_title']}",
  1075. "{video_dict['cover_url']}",
  1076. "{video_dict['video_url']}",
  1077. {int(duration)},
  1078. "{video_dict['publish_time']}",
  1079. {int(video_dict['play_cnt'])},
  1080. "{rule}",
  1081. {int(video_width)},
  1082. {int(video_height)}) """
  1083. MysqlHelper.update_values(log_type, crawler, sql, env, machine)
  1084. Common.logger(log_type, crawler).info('视频信息插入数据库成功!\n')
  1085. except Exception as e:
  1086. Common.logger(log_type, crawler).info(f"download_publish异常:{e}\n")
  1087. @classmethod
  1088. def get_follow_videos(cls, log_type, crawler, strategy, oss_endpoint, env, machine):
  1089. try:
  1090. user_list = cls.get_user_from_feishu(log_type, crawler, 'c467d7', env, machine)
  1091. if len(user_list) == 0:
  1092. Common.logger(log_type, crawler).warning('用户列表为空\n')
  1093. else:
  1094. for user_dict in user_list:
  1095. out_uid = user_dict['out_user_id']
  1096. user_name = user_dict['out_user_name']
  1097. browse_id = user_dict['out_browse_id']
  1098. our_uid = user_dict['our_user_id']
  1099. Common.logger(log_type, crawler).info(f'获取 {user_name} 主页视频\n')
  1100. cls.get_videos(log_type, crawler, strategy, oss_endpoint, env, browse_id, out_uid, our_uid, machine)
  1101. Common.logger(log_type, crawler).info('休眠 10 秒')
  1102. time.sleep(10)
  1103. cls.continuation = ''
  1104. except Exception as e:
  1105. Common.logger(log_type, crawler).error(f"get_follow_videos异常:{e}\n")
  1106. if __name__ == "__main__":
  1107. # print(Follow.get_browse_id('follow', 'youtube', '@chinatravel5971', "local"))
  1108. # print(Follow.get_user_from_feishu('follow', 'youtube', 'c467d7', 'dev', 'local'))
  1109. # Follow.get_out_user_info('follow', 'youtube', 'UC08jgxf119fzynp2uHCvZIg', '@weitravel')
  1110. # Follow.get_video_info('follow', 'youtube', 'OGVK0IXBIhI')
  1111. # Follow.get_follow_videos('follow', 'youtube', 'youtube_follow', 'out', 'dev', 'local')
  1112. # print(Follow.filter_emoji("姐妹倆一唱一和,完美配合,終於把大慶降服了😅😅#萌娃搞笑日常"))
  1113. # Follow.repeat_video('follow', 'youtube', 4, "dev", "local")
  1114. pass