youtube_follow_api.py 63 KB

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