youtube_follow.py 65 KB

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