YouTube API to fetch all videos on a channel - Stack Overflow
文章推薦指數: 80 %
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'.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://
延伸文章資訊
- 1About YouTube - YouTube
YouTube's mission is to give everyone a voice and show them the world. Learn about our brand, com...
- 210 Ways to Grow Your YouTube Channel | Blog - Digital ...
10 Ways to Grow Your YouTube Channel page on the Digital Marketing Institute Blog, all about keep...
- 3阿神
- 4瞭解頻道網址- YouTube說明
在「頻道網址」下方查看及複製頻道網址。 頻道網址(依據ID). 例如: youtube.com/channel/UCUZHFZ9jIKrLroW8LcyJEQQ. 這是YouTube 頻道所用的...
- 5建立YouTube 頻道
另外,即便你已擁有Google 帳戶,還是必須先建立YouTube 頻道,才能上傳影片、留言或建立播放清單。 如有需要,你可以在YouTube 電腦版網站或YouTube 行動版網站中建立頻道 ...