YouTube API to fetch all videos on a channel - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

eg https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails. Use this "uploads" Id to query PlaylistItems to get the ... 2022DeveloperSurveyisopen!Takesurvey. Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore YouTubeAPItofetchallvideosonachannel AskQuestion Asked 8years,7monthsago Modified 23daysago Viewed 309ktimes 270 122 WeneedavideolistbychannelnameofYouTube(usingtheAPI). Wecangetachannellist(onlychannelname)byusingthebelowAPI: https://gdata.youtube.com/feeds/api/channels?v=2&q=tendulkar Belowisadirectlinkofchannels https://www.youtube.com/channel/UCqAEtEr0A0Eo2IVcuWBfB9g Or WWW.YouTube.com/channel/HC-8jgBP-4rlI Now,weneedvideosofchannel>>UCqAEtEr0A0Eo2IVcuWBfB9gorHC-8jgBP-4rlI. Wetried https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&User=UC7Xayrf2k0NZiz3S04WuDNQ https://gdata.youtube.com/feeds/api/videos?v=2&uploader=partner&q=UC7Xayrf2k0NZiz3S04WuDNQ But,itdoesnothelp. Weneedallthevideospostedonthechannel.VideosuploadedtoachannelcanbefrommultipleusersthusIdon'tthinkprovidingauserparameterwouldhelp... youtubeyoutube-api Share Follow editedFeb22,2018at13:00 StephenKennedy 18.8k2222goldbadges9090silverbadges106106bronzebadges askedSep23,2013at7:07 RajendraDewaniRajendraDewani 2,88133goldbadges1313silverbadges88bronzebadges 1 canigetaccesstomyownvideofiles.toessentiallydownloadmyowncontentwhenloggedinviatheAPI!!! – filthy_wizard Dec23,2019at15:54 Addacomment  |  18Answers 18 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 268 YouneedtolookattheYouTubeDataAPI.YouwillfindtheredocumentationabouthowtheAPIcanbeaccessed.Youcanalsofindclientlibraries. Youcouldalsomaketherequestsyourself.HereisanexampleURLthatretrievesthelatestvideosfromachannel: https://www.googleapis.com/youtube/v3/search?key={your_key_here}&channelId={channel_id_here}&part=snippet,id&order=date&maxResults=20 AfterthatyouwillreceiveaJSONwithvideoidsanddetails,andyoucanconstructyourvideoURLlikethis: http://www.youtube.com/watch?v={video_id_here} Share Follow editedFeb21,2018at15:01 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredDec27,2013at6:00 akshayakshay 5,37855goldbadges3636silverbadges5656bronzebadges 17 38 ThiswillonlyreturnthefirstmaxResults=20(upto50)videos,butnottheentirechannelcatalogue.Ifyouwantmoreresults,usethepageTokenasdescribedhere. – FábioPerez Aug14,2014at15:12 3 RomulusUrakagiTs'ai:whilerequestingvideosyouaregivingchannelId,thatisthefilterforchannel. – akshay Nov19,2014at8:36 13 Worthnotingyoucanonlygetupto500videosfromachannelusingthenextpagetokens. – TonyPaternite Aug30,2016at1:21 11 bewareofusingsearchasithasaquotecostof100! – CMash Aug8,2019at15:55 4 Pleasenote:thesearchoperationisveryexpensive(100quota)comparedtotheoperationssuggestedbyjambrose(3+5quota)(asofmarch2020).SeeQuotaCalculator. – Teemoh Mar27,2020at4:57  |  Show12morecomments 182 First,youneedtogettheIDoftheplaylistthatrepresentstheuploadsfromtheuser/channel: https://developers.google.com/youtube/v3/docs/channels/list#try-it YoucanspecifytheusernamewiththeforUsername={username}param,orspecifymine=truetogetyourown(youneedtoauthenticatefirst).Includepart=contentDetailstoseetheplaylists. GEThttps://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=jambrose42&key={YOUR_API_KEY} Intheresult"relatedPlaylists"willinclude"likes"and"uploads"playlists.Grabthat"upload"playlistID.Alsonotethe"id"isyourchannelIDforfuturereference. Next,getalistofvideosinthatplaylist: https://developers.google.com/youtube/v3/docs/playlistItems/list#try-it JustdropintheplaylistId! GEThttps://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId=UUpRmvjdu3ixew5ahydZ67uA&key={YOUR_API_KEY} Share Follow editedNov15,2021at8:13 Soviut 83.6k4343goldbadges174174silverbadges239239bronzebadges answeredJan10,2015at2:27 jambrosejambrose 2,02111goldbadge1111silverbadges88bronzebadges 20 1 Noteveryonehasayoutubeusernameinthisbrandnewworld.Someofthemonlyhaveagoogle+useridnumber,whichdoesn'tworkintheplaceofayoutubeusername – kristopolous Mar22,2016at23:33 1 @kristopolousEveryYouTubechannelhasachannelID.IfyougotoaYouTubepageviaGoogleplus,itusestheGoogleplususeridasthelinktothechannel.IfyouwenttothechannelfromaYouTubevideo,itusesYouTube'schannelIDpropertyinstead. – Ignat Nov2,2016at1:35 42 Thisisperfect.Particularlybecauseitonlyspends2quotapointsinsteadof100(thatthesearchcallwouldspend). – JPdelaTorre Nov12,2016at10:28 2 somteimesit(developers.google.com/youtube/v3/docs/playlistItems/list#try-it)works,sometimesitthrows404forsameuploadId,don'tknowwhatsgoingon. – ishandutta2007 Apr23,2017at7:12 2 YoucanofcuseachannelIDtogetthisinformationinthefirstplace,justspecifytheidparameterinsteadofforUsername.Ifyou'reattemptingtogettheuploadplaylistformultiplechannelsatoncelikeIam,youcanspecifymultipleIDswitheitheracommaorusingtheidparametermultipletimes. – TrisT Jan4,2021at5:18  |  Show15morecomments 125 HereisavideofromGoogleDevelopersshowinghowtolistallvideosinachannelinv3oftheYouTubeAPI. Therearetwosteps: QueryChannelstogetthe"uploads"Id.eghttps://www.googleapis.com/youtube/v3/channels?id={channelId}&key={APIkey}&part=contentDetails Usethis"uploads"IdtoqueryPlaylistItemstogetthelistofvideos.eghttps://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads"Id}&key={APIkey}&part=snippet&maxResults=50 Share Follow editedJul11,2019at19:27 GeekyGuy 8,96844goldbadges4040silverbadges6161bronzebadges answeredApr3,2016at15:33 virtualmicvirtualmic 2,97466goldbadges2525silverbadges3434bronzebadges 8 1 Can"uploads"Idchangeforagivenchannel? – ishandutta2007 Apr23,2017at1:42 seemsuploadsaresameaschannelId,butterriblyinconsistentAPIs,cansomeanswerthisstackoverflow.com/questions/43568521/… – ishandutta2007 Apr23,2017at12:57 1 @ishandutta2007nouploadsidisdifferentfromchannelid. – vicke4 Apr29,2018at12:57 @virtualmic@PeterPerfectSolutionGuys,Thanks – AaskaPatel Jun11,2019at6:18 2 @MattBoothisspoton.ItseemsthepatternisChannelID=UC+{UserID},UploadPlaylistID=UU+{UserID}.I'mguessingit'sauto-generatedforeverychannelatthepointofcreation(orforoldchannels,whentheswitchhappenedfromYT'sAPItoGoogle's).Stillcan'tfindanysourcethatconfirmsit,butthroughtestingafewhundredchannels,theywereallfollowedthispattern.UCwouldmakesensetodenoteUserChannel,whileUUcouldbeUserUploads. – Scuilla Dec15,2020at21:14  |  Show3morecomments 43 Togetchannelslist: GetChannelslistbyforUserName: https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&forUsername=Apple&key= Getchannelslistbychannelid: https://www.googleapis.com/youtube/v3/channels/?part=snippet,contentDetails,statistics&id=UCE_M8A5yxnLfW0KghEeajjw&key= GetChannelsections: https://www.googleapis.com/youtube/v3/channelSections?part=snippet,contentDetails&channelId=UCE_M8A5yxnLfW0KghEeajjw&key= TogetPlaylists: GetPlaylistsbyChannelID: https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key= GetPlaylistsbyChannelIDwithpageToken: https://www.googleapis.com/youtube/v3/playlists?part=snippet,contentDetails&channelId=UCq-Fj5jknLsUf-MWSy4_brA&maxResults=50&key=&pageToken=CDIQAA TogetPlaylistItems: GetPlaylistItemslistbyPlayListId: https://www.googleapis.com/youtube/v3/playlistItems?part=snippet,contentDetails&maxResults=25&playlistId=PLHFlHpPjgk70Yv3kxQvkDEO5n5tMQia5I&key= Togetvideos: Getvideoslistbyvideoid: https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw&key= Getvideoslistbymultiplevideosid: https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=YxLCwfA1cLw,Qgy6LaO3SB0,7yPJXGO2Dcw&key= Getcommentslist GetCommentlistbyvideoID: https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&videoId=el****kQak&key=A**********k GetCommentlistbychannelID: https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&channelId=U*****Q&key=AI********k GetCommentlistbyallThreadsRelatedToChannelId: https://www.googleapis.com/youtube/v3/commentThreads?part=snippet,replies&allThreadsRelatedToChannelId=UC*****ntcQ&key=AI*****k Hereallapi'sareGetapproach. Basedonchannelidwecon'tgetallvideosdirectly,that'stheimportantpointhere. Forintegrationhttps://developers.google.com/youtube/v3/quickstart/ios?ver=swift Share Follow editedMay14,2019at4:48 answeredMar19,2019at12:50 NareshNaresh 14.5k55goldbadges8888silverbadges102102bronzebadges 2 Howcanisendmultiplechannelidstoapi,caniusecommaseparatedchannelids – OnkarMusale Jan1,2020at10:55 Howcanigetthetop10/50/100youtubechannelsusingapi? – Rajeshwar Jun6,2020at9:31 Addacomment  |  12 Hereisthecodethatwillreturnallvideoidsunderyourchannel $channelId, 'part'=>'contentDetails', 'key'=>$apiKey ]; $url=$baseUrl.'channels?'.http_build_query($params); $json=json_decode(file_get_contents($url),true); $playlist=$json['items'][0]['contentDetails']['relatedPlaylists']['uploads']; $params=[ 'part'=>'snippet', 'playlistId'=>$playlist, 'maxResults'=>'50', 'key'=>$apiKey ]; $url=$baseUrl.'playlistItems?'.http_build_query($params); $json=json_decode(file_get_contents($url),true); $videos=[]; foreach($json['items']as$video) $videos[]=$video['snippet']['resourceId']['videoId']; while(isset($json['nextPageToken'])){ $nextUrl=$url.'&pageToken='.$json['nextPageToken']; $json=json_decode(file_get_contents($nextUrl),true); foreach($json['items']as$video) $videos[]=$video['snippet']['resourceId']['videoId']; } print_r($videos); Note:Youcangetchannelidat https://www.youtube.com/account_advancedafterloggedin. Share Follow answeredJan18,2017at9:42 MihirBhattMihirBhatt 2,72922goldbadges3434silverbadges4141bronzebadges 2 1 Thisoneisdefinitelyacleansolutionthatworks.Currentlyusinginproduction. – Codex73 Jun28,2019at15:51 thanksman,itreallyworksjustpastedandeverythingworksgreat! – Asylzat Oct12,2020at5:37 Addacomment  |  11 BelowisaPythonalternativethatdoesnotrequireanyspecialpackages.Byprovidingthechanneliditreturnsalistofvideolinksforthatchannel.PleasenotethatyouneedanAPIKeyforittowork. importurllib importjson defget_all_video_in_channel(channel_id): api_key=YOURAPIKEY base_video_url='https://www.youtube.com/watch?v=' base_search_url='https://www.googleapis.com/youtube/v3/search?' first_url=base_search_url+'key={}&channelId={}&part=snippet,id&order=date&maxResults=25'.format(api_key,channel_id) video_links=[] url=first_url whileTrue: inp=urllib.urlopen(url) resp=json.load(inp) foriinresp['items']: ifi['id']['kind']=="youtube#video": video_links.append(base_video_url+i['id']['videoId']) try: next_page_token=resp['nextPageToken'] url=first_url+'&pageToken={}'.format(next_page_token) except: break returnvideo_links Share Follow answeredNov14,2017at16:32 StianStian 68677silverbadges1010bronzebadges 3 Howdoesthiswork?IpastedtheAPIKEYusingsinglequotes''intotheapi_keyvariable,thenIcalledthefunctionpassinginthechannelid,thenranthepythonprogram,butnothinghappens. – JoffreyBaratheon Apr27,2018at0:33 @JoffreyBaratheonthefunctionreturnanarray,youneedtocontainthattoavariable.Forexample:video_list=get_all_video_in_channel("ABC123EFG456")thenyoucouldprintittoseethearrayusingprint(video_list) – phaphapha May3,2018at2:05 Eventhoughthismightbethequickestway,thecostof"search"is100unitandthatmayresultquotaexceed. – YasinOkumuş Sep27,2020at0:42 Addacomment  |  7 Thankstothereferencessharedhereandelsewhere,I'vemadeanonlinescript/toolthatonecanusetoobtainallvideosofachannel. ItcombinesAPIcallstoyoutube.channels.list,playlistItems,videos.Itusesrecursivefunctionstomaketheasynchronouscallbacksrunthenextiterationupongettingavalidresponse. Thisalsoservestolimittheactualnumberofrequestsmadeatatime,hencekeepingyousafefromviolatingYouTubeAPIrules.Sharingshortenedsnippetsandthenalinktothefullcode.Igotaroundthe50maxresultspercalllimitationbyusingthenextPageTokenvaluethatcomesintheresponsetofetchthenext50resultsandsoon. functiongetVideos(nextPageToken,vidsDone,params){ $.getJSON("https://www.googleapis.com/youtube/v3/playlistItems",{ key:params.accessKey, part:"snippet", maxResults:50, playlistId:params.playlistId, fields:"items(snippet(publishedAt,resourceId/videoId,title)),nextPageToken", pageToken:(nextPageToken||'') }, function(data){ //commandstoprocessJSONvariable,extractthe50videosinfo if(vidsDone https://www.googleapis.com/youtube/v3/subscriptions?part=snippet&maxResults=50&mine=true&access_token={oauth_token} Channels:list-> https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id={channel_id}&key={YOUR_API_KEY} PlaylistItems:list-> https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId={playlist_id}&key={YOUR_API_KEY} Share Follow editedFeb21,2018at15:03 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredJul28,2015at15:19 sacred0x01sacred0x01 30222silverbadges1111bronzebadges 1 Andhowdoyouresolvetheplaylist_idfromthechannellist? – Emiswelt Oct4,2021at6:59 Addacomment  |  5 Sinceeveryoneansweringthisquestionhasproblemsduetothe500videolimithere'sanalternatesolutionusingyoutube_dlinPython3.Also,noAPIkeyisneeded. Installyoutube_dl:sudopip3installyoutube-dl Findoutyourtargetchannel'schannelid.TheIDisgoingtostartwithUC.ReplacetheCforChannelwithUforUpload(i.e.UU...),thisistheuploadplaylist. Usetheplaylistdownloaderfeaturefromyoutube-dl.IdeallyyoudoNOTwanttodownloadeveryvideointheplaylistwhichisthedefault,butonlythemetadata. Example(warning--takestensofminutes): importyoutube_dl,pickle #UCVTyTA7-g9nopHeHbeuvpRAisthechannelid(1517+videos) PLAYLIST_ID='UUVTyTA7-g9nopHeHbeuvpRA'#LateNightwithSethMeyers withyoutube_dl.YoutubeDL({'ignoreerrors':True})asydl: playd=ydl.extract_info(PLAYLIST_ID,download=False) withopen('playlist.pickle','wb')asf: pickle.dump(playd,f,pickle.HIGHEST_PROTOCOL) vids=[vidforvidinplayd['entries']if'ACloserLook'invid['title']] print(sum('Trump'invid['title']forvidinvids),'/',len(vids)) Share Follow editedFeb21,2018at15:10 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredJun14,2017at0:00 xjclxjcl 9,26855goldbadges5353silverbadges6363bronzebadges 2 1 Ithinkthisisthebestanswersinceitdoesn'tneedAPIkey.Tomakeitevenmoreautomatedyoucanuse@for/f"usebackqtokens=2delims=:"%ain(`dl-list.py^|findstrinformation`)do@echohttps://www.youtube.com/watch?v=%a.ItwillprintalltheURLofthevideos.PLAYLIST_IDcanbeaplaylistorchannelID. – cdlvcdlv May26,2018at20:41 YoucaninferitbutIforgottosaythatIsavedthecodeasdl-list.py. – cdlvcdlv May26,2018at20:49 Addacomment  |  5 Shortanswer: Here'salibrarycalledscrapetubeThatcanhelpwiththat. pipinstallscrapetube importscrapetube videos=scrapetube.get_channel("UC9-y-6csu5WGm29I7JiwpnA") forvideoinvideos: print(video['videoId']) Longanswer: Themodulementionedabovewascreatedbymeduetoalackofanyothersolutions.Here'swhatitried: Selenium.Itworkedbuthadthreebigdrawbacks:1.Itrequiresawebbrowseranddrivertobeinstalled.2.hasbigCPUandmemoryrequirements.3.can'thandlebigchannels. Usingyoutube-dl.Likethis: importyoutube_dl youtube_dl_options={ 'skip_download':True, 'ignoreerrors':True } withyoutube_dl.YoutubeDL(youtube_dl_options)asydl: videos=ydl.extract_info(f'https://www.youtube.com/channel/{channel_id}/videos') Thisalsoworksforsmallchannels,butforbiggeronesiwouldgetblockedbyyoutubeformakingsomanyrequestsinsuchashorttime(becauseyoutube-dldownloadsmoreinfoforeveryvideointhechannel). SoimadethelibraryscrapetubewhichusesthewebAPItogetallthevideos. Share Follow editedApr5at20:40 GedFlod 76311goldbadge77silverbadges2222bronzebadges answeredJul28,2021at10:06 dermasmiddermasmid 15133silverbadges55bronzebadges Addacomment  |  2 UsingAPIversion2,whichisdeprecated,theURLforuploads(ofchannelUCqAEtEr0A0Eo2IVcuWBfB9g)is: https://gdata.youtube.com/feeds/users/UCqAEtEr0A0Eo2IVcuWBfB9g/uploads ThereisanAPIversion3. Share Follow editedFeb21,2018at14:59 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredOct10,2013at16:11 AlsAls 1,37711goldbadge1010silverbadges55bronzebadges 3 ForUCqAEtEr0A0Eo2IVcuWBfB9gitworks,ithinkthisisbecauseitsuploadedbyasingleuser.HowaboutHC-8jgBP-4rlI – RajendraDewani Oct16,2013at7:18 Didn'tcheckmymessagesuntiltoday.You'reright.Onlyforanuserchannel. – Als Mar1,2014at11:09 12 Thelinkisdead. – user3078414 Jul16,2016at10:29 Addacomment  |  2 RecentlyIhadtoretrieveallvideosfromachannel,andaccordingtoYouTubedeveloperdocumentation: https://developers.google.com/youtube/v3/docs/playlistItems/list functionplaylistItemsListByPlaylistId($service,$part,$params){ $params=array_filter($params); $response=$service->playlistItems->listPlaylistItems( $part, $params ); print_r($response); } playlistItemsListByPlaylistId($service, 'snippet,contentDetails', array('maxResults'=>25,'playlistId'=>'idof"uploads"playlist')); Where$serviceisyourGoogle_Service_YouTubeobject. Soyouhavetofetchinformationfromthechanneltoretrievethe"uploads"playlistthatactuallyhasallthevideosuploadedbythechannel:https://developers.google.com/youtube/v3/docs/channels/list IfnewwiththisAPI,Ihighlyrecommendtoturnthecodesamplefromthedefaultsnippettothefullsample. Sothebasiccodetoretrieveallvideosfromachannelcanbe: classYouTube { constDEV_KEY='YOUR_DEVELOPPER_KEY'; private$client; private$youtube; private$lastChannel; publicfunction__construct() { $this->client=newGoogle_Client(); $this->client->setDeveloperKey(self::DEV_KEY); $this->youtube=newGoogle_Service_YouTube($this->client); $this->lastChannel=false; } publicfunctiongetChannelInfoFromName($channel_name) { if($this->lastChannel&&$this->lastChannel['modelData']['items'][0]['snippet']['title']==$channel_name) { return$this->lastChannel; } $this->lastChannel=$this->youtube->channels->listChannels('snippet,contentDetails,statistics',array( 'forUsername'=>$channel_name, )); return($this->lastChannel); } publicfunctiongetVideosFromChannelName($channel_name,$max_result=5) { $this->getChannelInfoFromName($channel_name); $params=[ 'playlistId'=>$this->lastChannel['modelData']['items'][0]['contentDetails']['relatedPlaylists']['uploads'], 'maxResults'=>$max_result, ]; return($this->youtube->playlistItems->listPlaylistItems('snippet,contentDetails',$params)); } } $yt=newYouTube(); echo'

'.print_r($yt->getVideosFromChannelName('CHANNEL_NAME'),true).'
'; Share Follow editedFeb21,2018at15:07 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredMay23,2017at8:17 GlastisGlastis 15333silverbadges1414bronzebadges 1 Doesthisgetallthevideoswithtitles,URLofthevideo,animageidentifyingthevideo,numberoflikes/comments?Someinfoonhowthispublisheswouldbehelpful.Thanks. – KhomNazid Jun7,2019at23:23 Addacomment  |  1 SamplesolutioninPython.Helptakenfromthisvideo:video Likemanyotheranswers,uploadidistoberetrievedfromthechannelidfirst. importurllib.request importjson key="YOUR_YOUTUBE_API_v3_BROWSER_KEY" #Listofchannels:mentionifyouarepastingchannelidorusername-"id"or"forUsername" ytids=[["bbcnews","forUsername"],["UCjq4pjKj9X4W9i7UnYShpVg","id"]] newstitles=[] forytid,ytparaminytids: urld="https://www.googleapis.com/youtube/v3/channels?part=contentDetails&"+ytparam+"="+ytid+"&key="+key withurllib.request.urlopen(urld)asurl: datad=json.loads(url.read()) uploadsdet=datad['items'] #getuploadidfromchannelid uploadid=uploadsdet[0]['contentDetails']['relatedPlaylists']['uploads'] #retrievelist urld="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId="+uploadid+"&key="+key withurllib.request.urlopen(urld)asurl: datad=json.loads(url.read()) fordataindatad['items']: ntitle=data['snippet']['title'] nlink=data['contentDetails']['videoId'] newstitles.append([nlink,ntitle]) forlink,titleinnewstitles: print(link,title) Share Follow answeredApr14,2019at8:55 AnanthAnanth 1,54222goldbadges1010silverbadges77bronzebadges Addacomment  |  1 Fromhttps://stackoverflow.com/a/65440501/2585501: Thismethodisespeciallyusefulifa)thechannelhasmorethan50videosorifb)desireyoutubevideoidsformattedinaflattxtlist: ObtainaYoutubeAPIv3key(seehttps://stackoverflow.com/a/65440324/2585501) ObtaintheYoutubeChannelIDofthechannel(seehttps://stackoverflow.com/a/16326307/2585501) ObtaintheUploadsPlaylistIDofthechannel:https://www.googleapis.com/youtube/v3/channels?id={channelId}&key={APIkey}&part=contentDetails(basedonhttps://www.youtube.com/watch?v=RjUlmco7v2M) Installyoutube-dl(e.g.pip3install--upgradeyoutube-dlorsudoapt-getinstallyoutube-dl) DownloadtheUploadsPlaylistusingyoutube-dl:youtube-dl-j--flat-playlist"https://"|jq-r'.id'|sed's_^_https://youtu.be/_'>videoList.txt(seehttps://superuser.com/questions/1341684/youtube-dl-how-download-only-the-playlist-not-the-files-therein) Share Follow answeredDec24,2020at15:51 user2585501user2585501 52833silverbadges1616bronzebadges 1 ToDownloadtheListonecanuseYoutubeAPI,too.Thereisnoneedtouseadditionaltoolslikeyoutube-dl – Tom Jan31at9:59 Addacomment  |  1 Postinglongaftertheoriginalquestionwasasked,butImadeapythonpackagethatdoesthisusingaverysimpleAPI.Itgetsallthevideosuploadedtoachannel,butI'mnotsureaboutthispart(includedintheoriginalquestion): VideosuploadedtoachannelcanbefrommultipleusersthusIdon'tthinkprovidingauserparameterwouldhelp... MaybeYouTubechangedinthe8yearssincethisquestionwasposted,butifitdidn't,thepackageImademightnotcoverthiscase. TousetheAPI: pip3install-Uyt-videos-list#macOS pipinstall-Uyt-videos-list#Windows #ifthatdoesn'twork,try python3-mpipinstall-Uyt-videos-list#macOS python-mpipinstall-Uyt-videos-list#Windows Thenopenupapythoninterpreter python3#macOS python#Windows andruntheprogram: fromyt_videos_listimportListCreator lc=ListCreator() help(lc)#displayAPIinformation-showsavailableparametersandfunctions my_url='https://www.youtube.com/user/1veritasium' lc.create_list_for(url=my_url) Pythondocumentation(willbeupdatedmostfrequently,socheckthispageforupdates!) Repositoryhomepage PyPIpage Share Follow answeredSep8,2021at6:39 slow-but-steadyslow-but-steady 74377silverbadges1212bronzebadges Addacomment  |  0 That'smyPythonsolution,usingGoogleAPI. Observations: Createa.envfiletostoreyourAPIDeveloperKey,andputitinyour.gitignorefile Theparameter"forUserName"shouldbesetwiththenameoftheYoutubeChannel(username).Alternatively,youcanusethechannelid,settingtheparameter"id",insteadof"forUserName". Theobject"playlistItem"givesyouaccesstoeachvideo.I'mshowingonlyitstitlebuttherearemanyotherproperties. importos importgoogleapiclient.discovery fromdecoupleimportconfig defmain(): os.environ["OAUTHLIB_INSECURE_TRANSPORT"]="1" api_service_name="youtube" api_version="v3" DEVELOPER_KEY=config('API_KEY') youtube=googleapiclient.discovery.build( api_service_name,api_version,developerKey=DEVELOPER_KEY) request=youtube.channels().list( part="contentDetails", forUsername="username", #id="oiwuereru8987", ) response=request.execute() foriteminresponse['items']: playlistId=item['contentDetails']['relatedPlaylists']['uploads'] nextPageToken='' while(nextPageToken!=None): playlistResponse=youtube.playlistItems().list( part='snippet', playlistId=playlistId, maxResults=25, pageToken=nextPageToken ) playlistResponse=playlistResponse.execute() print(playlistResponse.keys()) foridx,playlistIteminenumerate(playlistResponse['items']): print(idx,playlistItem['snippet']['title']) if'nextPageToken'inplaylistResponse.keys(): nextPageToken=playlistResponse['nextPageToken'] else: nextPageToken=None if__name__=="__main__": main() Exampleforthe.envfile API_KEY= Share Follow editedApr24at14:10 answeredApr24at0:13 JoséFlorenciodeQueirozJoséFlorenciodeQueiroz 14411silverbadge55bronzebadges Addacomment  |  -7 Asthedocumentationstates(link),youcanusethechannelresourcetypeandoperationListtogetallthevideosinanchannel.Thisoperationmustbeperformedusingargument'channelid'. Share Follow editedFeb21,2018at15:00 PeterMortensen 30k2121goldbadges100100silverbadges124124bronzebadges answeredOct10,2013at16:46 SinghSingh 2,06133goldbadges1515silverbadges3030bronzebadges 1 25 Itiseasytosay,butwhydon`tyouputyouranswerwithagoodandworkingexample??? – akshay Dec27,2013at5:56 Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedyoutubeyoutube-apioraskyourownquestion. TheOverflowBlog Open-sourceiswinningoverdevelopersandinvestors(Ep.442) Stackunderattack:whatwelearnedabouthandlingDDoSattacks FeaturedonMeta RetiringCommunity-SpecificClosureReasonsforServerFaultandSuperUser StagingGround:ReviewerMotivation,Scaling,andOpenQuestions Linked 0 JavaScript:ImportvideofromyoutubechannelsasAPIjsontomywebsite 123 HowcanIgetachannelIDfromYouTube? 88 HowtogetnumberofvideoviewswithYouTubeAPI? 67 Youtubeapiv3Getlistofuser'svideos 12 HowcanIgetallvideosID'sfromaYoutubechannel 5 Getlistofvideofromayoutubechannel 9 Youtube/v3/searchAPInolongerreturninglivevideos 3 WheretofindtheyoutubeAPIKey? 2 YoutubeAPIv3geteveryVideoIDfromgivenchannel 3 Youtubeapidisplaylimitedvideosfromuser'splaylistandroid Seemorelinkedquestions Related 2678 HowdoIgetaYouTubevideothumbnailfromtheYouTubeAPI? 12 HowcanIgetallvideosID'sfromaYoutubechannel 6 GetXMLwithid'sofalluploadedvideosonyoutubechannel 123 HowcanIgetachannelIDfromYouTube? 15 HowtogetYoutubechannelbannerusingYoutubeAPI? 3 Youtubeapidisplaylimitedvideosfromuser'splaylistandroid 2 Whatisdifferenceof"Postedvideo"and"Uploads"inYouTubeChannel?AndhowtogetthemthroughYouTubeDatav3API? 5 YouTubeApiv3-topicchannelvideos 20 HowtogetYoutubechanneldetailsusingYoutubedataAPIifchannelhascustomurl 0 WhyistheYoutubeV3DataAPIonlyreturning1videoresultforthischannel? HotNetworkQuestions Toggle2LEDsusingatimerXMEGA-A3BUXplained Anaffixriddletodipinto Asanewemployeeofalargecorporation,whatcanIdoaboutsomedisagreementswiththecompany'scodeofconduct? CanMathematicacalculatethis? Wouldalowergravityplanethavedeeperoceansandhighercontinents? WhyhaveMS-DOSdevicedriversiftheROMBIOSprovidesaccesstothesamedevicesalready? Whichtopologyismoreoptimized/recommendedtoworkwith? Shouldcyclistonabikepathseparatedfromtheroadovertakeeachotherontherightorontheleft? WhatshouldIcallmymathematicsthesis's1stchapterthatcoversbackgroundconcepts? SchengenVisa0003underRemarks TracingtheclassicalreasonerinIsabelle Istheidealproductpresheafasheaf?Dowehaveanyreasonstobelieveitwillbe/itwon't? FailureofNewton'scorpusculartheoryandsuccessofphotontheoryoflight DidRussiaoncewanttojoinNATO?DoesformerRussianPrimeMinisterMikhailKasyanovrefertoaseriousinterestinthepast? Wouldliketochangea230Volt12/2into2each115Voltseparatepluglineswithouthavingtorunanother12/3frompanel? Whydoesn'tapianohavedampersintheupperregister? WhatdoesitmeaniftheFermilevelcrossesintothevalenceband?Howaboutintotheconductionband? Cantherighttoself-representbewaivedduetoconflictofinterest? Teammemberregularlyignores"backtooffice"policy HowcanIcapitaliseawordproceedingaspecificword Whyisasetwithoneelementdistinctfromtheelementitself? Usingneitheraloneinasentence Conflictingadviceonwhichknifetousewhencuttingupachicken,whichshouldIuse? Mysisterwantstoplayeveryotherweekatourweeklytable.HowdoIfixtheissuesthatcomewiththis? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?