44

I want to extract the Title of YouTube's videos. How can I do this?

Thanks.

Naman
  • 1,519
  • 18
  • 32
webkul
  • 2,836
  • 10
  • 47
  • 61
  • every time when u open the youtube it shows a title below the title the video is embed – webkul Aug 01 '09 at 07:16
  • See also: http://stackoverflow.com/questions/2068344/how-do-i-get-a-youtube-video-thumbnail-from-the-youtube-api – Salman A Nov 18 '14 at 05:21

19 Answers19

70

Easiest way to obtain information about a youtube video afaik is to parse the string retrieved from: http://youtube.com/get_video_info?video_id=XXXXXXXX

Using something like PHP's parse_str(), you can obtain a nice array of nearly anything about the video:

$content = file_get_contents("http://youtube.com/get_video_info?video_id=".$id);
parse_str($content, $ytarr);
echo $ytarr['title'];

That will print the title for the video using $id as the video's id.

Cruel
  • 2,444
  • 2
  • 18
  • 18
  • This method is very convenient. Is there any official documentation on this method? Thanks. – sharat87 May 11 '11 at 16:08
  • 1
    There isn't as far as I can tell, which leads me to believe it may not actually be _the best_ method, since the get_video_info could very well die just like get_video did. However, using this method you can access some info not provided in official API (such as direct stream URL for downloading Youtube videos, like get_video provided). Short solution: If official Youtube API (like Alex.Bullard answered here) doesn't provide the desired information, try probing get_video_info – Cruel May 23 '11 at 01:49
  • Thanks @Cruel, that's just the info I needed :) – sharat87 May 23 '11 at 14:03
  • helped me today :) +1 – Sajad Karuthedath Jan 02 '15 at 05:55
  • Returns 410 NoLongerAvailableException now – zfj3ub94rf576hc4eegm Dec 30 '16 at 03:30
  • I just tried with one video ID and it still worked for me: http://youtube.com/get_video_info?video_id=dDEtGLQLEi8 However, it's very possible Youtube is phasing this out. I believe they would favor usage of official API. – Cruel Dec 31 '16 at 04:01
  • Worked for my Extension - Thank You! – Marco Jun 28 '17 at 20:42
  • This should really be done over https://. They redirect you there anyway – Stefan Reich Oct 31 '17 at 00:04
  • 1
    @black_belt I know your comment is quite old and you may have realized this by now, but it is quite possible the OP wasn't designing for a page with PHP access. – Abandoned Cart Jul 05 '18 at 15:39
  • 1
    just after parse_str() we need : $jsondec = json_decode($ytarr['player_response'],true); echo $jsondec['videoDetails'][title]; I have edited the answer. – Sunil Kumar Aug 21 '19 at 07:23
  • @SunilKumar what happened to your edit? Can't see it in the history either. – Sz. Jul 05 '20 at 12:48
  • @Sz. I am not sure. – Sunil Kumar Jul 06 '20 at 04:39
  • 2
    Is this out of date? That url now gives a 410, moved or deleted. – Goose Jul 06 '22 at 15:07
14

Hello In python3 i founded 2 ways

1) without API KEY

import urllib.request
import json
import urllib
import pprint

#change to yours VideoID or change url inparams
VideoID = "SZj6rAYkYOg" 

params = {"format": "json", "url": "https://www.youtube.com/watch?v=%s" % VideoID}
url = "https://www.youtube.com/oembed"
query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string

with urllib.request.urlopen(url) as response:
    response_text = response.read()
    data = json.loads(response_text.decode())
    pprint.pprint(data)
    print(data['title'])

example results:

{'author_name': 'Google Developers',
 'author_url': 'https://www.youtube.com/user/GoogleDevelopers',
 'height': 270,
 'html': '<iframe width="480" height="270" '
         'src="https://www.youtube.com/embed/SZj6rAYkYOg?feature=oembed" '
         'frameborder="0" allow="autoplay; encrypted-media" '
         'allowfullscreen></iframe>',
 'provider_name': 'YouTube',
 'provider_url': 'https://www.youtube.com/',
 'thumbnail_height': 360,
 'thumbnail_url': 'https://i.ytimg.com/vi/SZj6rAYkYOg/hqdefault.jpg',
 'thumbnail_width': 480,
 'title': 'Google I/O 101:  Google APIs: Getting Started Quickly',
 'type': 'video',
 'version': '1.0',
 'width': 480}
Google I/O 101:  Google APIs: Getting Started Quickly

2) Using Google API - required APIKEY

import urllib.request
import json
import urllib
import pprint

APIKEY = "YOUR_GOOGLE_APIKEY"
VideoID = "YOUR_VIDEO_ID"

params = {'id': VideoID, 'key': APIKEY,
          'fields': 'items(id,snippet(channelId,title,categoryId),statistics)',
          'part': 'snippet,statistics'}

url = 'https://www.googleapis.com/youtube/v3/videos'

query_string = urllib.parse.urlencode(params)
url = url + "?" + query_string

with urllib.request.urlopen(url) as response:
    response_text = response.read()
    data = json.loads(response_text.decode())
    pprint.pprint(data)
    print("TITLE: %s " % data['items'][0]['snippet']['title'])

example results:

{'items': [{'id': 'SZj6rAYkYOg',
            'snippet': {'categoryId': '28',
                        'channelId': 'UC_x5XG1OV2P6uZZ5FSM9Ttw',
                        'title': 'Google I/O 101:  Google APIs: Getting '
                                 'Started Quickly'},
            'statistics': {'commentCount': '36',
                           'dislikeCount': '20',
                           'favoriteCount': '0',
                           'likeCount': '418',
                           'viewCount': '65783'}}]}
TITLE: Google I/O 101:  Google APIs: Getting Started Quickly
porto
  • 555
  • 4
  • 7
9

Using JavaScript data API:

var loadInfo = function (videoId) {
    var gdata = document.createElement("script");
    gdata.src = "http://gdata.youtube.com/feeds/api/videos/" + videoId + "?v=2&alt=jsonc&callback=storeInfo";
    var body = document.getElementsByTagName("body")[0];
    body.appendChild(gdata);
};

var storeInfo = function (info) {
    console.log(info.data.title);
};

Then you just need to call loadInfo(videoId).

More informations are available on the API documentation.

sirLisko
  • 1,394
  • 10
  • 13
  • 1
    YouTube shut down the old APIs. Take a look here for more info about the new version https://developers.google.com/youtube/v3/getting-started. – sirLisko May 30 '17 at 13:35
8

One way to do this would be to retrieve the video from youtube as shown here

Then extract the title out of the atom feed sent by youtube. A sample feed is shown here

Alex.Bullard
  • 5,533
  • 2
  • 25
  • 32
6

I'll lay out the process as outlined by the YouTube API v3 documentation.

  1. Make a / login to the Google account that you want to be associated with your YouTube API use.
  2. Create a new project at https://console.developers.google.com/apis/credentials.

    • On the upper left, next to the Google APIs logo, go to Select a project and Create project +.
    • Wait a moment for the creation to finish.
  3. Make a new API key. You'll need it to access video info under v3.

    • If you're not already there, go to Credentials under the navigator on the left hand side, APIs and Services > Credentials.
    • Under the Credentials tab, click Create Credentials and select API key.
    • Copy the API key to your clipboard.
  4. Providing a video ID and your newly created API key, go to this link to see your work in action: https://www.googleapis.com/youtube/v3/videos?id=<YOUR VIDEO ID HERE>&key=<YOUR API KEY HERE>%20&part=snippet (no angle brackets)

Example

The URL is, well, what URL you can go to through your browser to check it out. In return, you should get what's under API response:.

URL: https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY
     &fields=items(id,snippet(channelId,title,categoryId),statistics)&part=snippet,statistics

Description: This example modifies the fields parameter from example 3
             so that in the API response, each video resource's snippet
             object only includes the channelId, title,
             and categoryId properties.

API response:

{
 "videos": [
  {
   "id": "7lCDEYXw3mM",
   "snippet": {
    "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
    "title": "Google I/O 101: Q&A On Using Google APIs",
    "categoryId": "28"
   },
   "statistics": {
    "viewCount": "3057",
    "likeCount": "25",
    "dislikeCount": "0",
    "favoriteCount": "17",
    "commentCount": "12"
   }
  }
 ]
}

This gives you video info in the .json file format. If your project is to access this info through JavaScript, you may be going here next: How to get JSON from URL in Javascript?.

llf
  • 610
  • 10
  • 11
5

I believe the best way is to use youTube's gdata, and then grab info from XML that is returned

http://gdata.youtube.com/feeds/api/videos/6_Ukfpsb8RI

Update: There is a newer API out now which you should use instead

https://developers.google.com/youtube/v3/getting-started

URL: https://www.googleapis.com/youtube/v3/videos?id=7lCDEYXw3mM&key=YOUR_API_KEY
     &fields=items(id,snippet(channelId,title,categoryId),statistics)&part=snippet,statistics

Description: This example modifies the fields parameter from example 3 so that in the API response, each video resource's snippet object only includes the channelId, title, and categoryId properties.

API response:

{
 "videos": [
  {
   "id": "7lCDEYXw3mM",
   "snippet": {
    "channelId": "UC_x5XG1OV2P6uZZ5FSM9Ttw",
    "title": "Google I/O 101: Q&A On Using Google APIs",
    "categoryId": "28"
   },
   "statistics": {
    "viewCount": "3057",
    "likeCount": "25",
    "dislikeCount": "0",
    "favoriteCount": "17",
    "commentCount": "12"
   }
  }
 ]
}
abritez
  • 2,616
  • 3
  • 29
  • 36
4
// This is the youtube video URL: http://www.youtube.com/watch?v=nOHHta68DdU
$code = "nOHHta68DdU";
// Get video feed info (xml) from youtube, but only the title | http://php.net/manual/en/function.file-get-contents.php
$video_feed = file_get_contents("http://gdata.youtube.com/feeds/api/videos?v=2&q=".$code."&max-results=1&fields=entry(title)&prettyprint=true");
// xml to object | http://php.net/manual/en/function.simplexml-load-string.php
$video_obj = simplexml_load_string($video_feed);
// Get the title string to a variable
$video_str = $video_obj->entry->title;
// Output
echo $video_str;
glocsw
  • 462
  • 4
  • 4
4

With bash, wget and lynx:

#!/bin/bash
read -e -p "Youtube address? " address
page=$(wget "$address" -O - 2>/dev/null)
title=$(echo "$page" | grep "   - ")
title="$(lynx --dump -force-html <(echo "<html><body>
$title
</body></html>")| grep "  - ")"
title="${title/*   - /}"
echo "$title"
dropped
  • 41
  • 1
3

If python batch processing script is appreciated: I used BeautifulSoup to easily parse the title from HTML, urllib to download the HTML and unicodecsv libraries in order to save all the characters from Youtube title.

The only thing you need to do is to place csv with single (named) column url with URLs of the Youtube videos in the same folder as the script is and name it yt-urls.csv and run the script. You will get file yt-urls-titles.csv containing the URLs and its titles.

#!/usr/bin/python

from bs4 import BeautifulSoup
import urllib
import unicodecsv as csv

with open('yt-urls-titles.csv', 'wb') as f:
    resultcsv = csv.DictWriter(f, delimiter=';', quotechar='"',fieldnames=['url','title'])
    with open('yt-urls.csv', 'rb') as f:
        inputcsv = csv.DictReader(f, delimiter=';', quotechar='"')
        resultcsv.writeheader()
        for row in inputcsv:
            soup = BeautifulSoup(urllib.urlopen(row['url']).read(), "html.parser")
            resultcsv.writerow({'url': row['url'],'title': soup.title.string})
Matěj M
  • 89
  • 1
  • 5
2

If you have youtube-dl, it's as simple as:

youtube-dl --get-title https://www.youtube.com/watch?v=dQw4w9WgXcQ
daviewales
  • 2,144
  • 21
  • 30
1

Here's some cut and paste code for ColdFusion:

http://trycf.com/gist/f296d14e456a7c925d23a1282daa0b90

It works on CF9 (and likely, earlier versions) using YouTube API v3, which requires an API key.

I left some comments and diag stuff in it, for anyone who wants to dig deeper. Hope it helps someone.

1

You can do using Json to get the all info about video

$jsonURL = file_get_contents("https://www.googleapis.com/youtube/v3/videos?id={Your_Video_ID_Here}&key={Your_API_KEY}8&part=snippet");
$json = json_decode($jsonURL);

$vtitle = $json->{'items'}[0]->{'snippet'}->{'title'};
$vdescription = $json->{'items'}[0]->{'snippet'}->{'description'};
$vvid = $json->{'items'}[0]->{'id'};
$vdate = $json->{'items'}[0]->{'snippet'}->{'publishedAt'};
$vthumb = $json->{'items'}[0]->{'snippet'}->{'thumbnails'}->{'high'}->{'url'};

I hope it will solve your problem.

Shahzaib Chadhar
  • 178
  • 1
  • 10
1

using python i got itimport pafy url = "https://www.youtube.com/watch?v=bMt47wvK6u0" video = pafy.new(url) print(video.title)

0

If you are familiar with java, try the Jsoup parser.

Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();
Sorter
  • 9,704
  • 6
  • 64
  • 74
0

Try this, I am getting name and url of each video in a playlist, you can modify this code as per your requirement.

$Playlist = ((Invoke-WebRequest "https://www.youtube.com/watch?v=HKkRbc6W6NA&list=PLz9M61O0WZqSUvHzPHVVC4IcqA8qe5K3r&
index=1").Links | Where {$_.class -match "playlist-video"}).href
$Fname = ((Invoke-WebRequest "https://www.youtube.com/watch?v=HKkRbc6W6NA&list=PLz9M61O0WZqSUvHzPHVVC4IcqA8qe5K3r&ind
ex=1").Links | Where {$_.class -match "playlist-video"}).outerText
$FinalText=""
For($i=0;$i -lt $playlist.Length;$i++)
{
Write-Output("'"+($Fname[$i].split("|")[0]).split("|")[0]+"'+"+"https://www.youtube.com"+$Playlist[$i])
}
Graham
  • 7,431
  • 18
  • 59
  • 84
Ajay Sharma
  • 31
  • 1
  • 6
0

JavaX now ships with this function. Showing a video's thumbnail and title, for example, is a two-liner:

SS map = youtubeVideoInfo("https://www.youtube.com/watch?v=4If_vFZdFTk"));
showImage(map.get("title"), loadImage(map.get("thumbnail_url")));

Example

Stefan Reich
  • 1,000
  • 9
  • 12
0

Similarly to Matej M, but more simply:

import requests
from bs4 import BeautifulSoup


def get_video_name(id: str):
    """
    Return the name of the video as it appears on YouTube, given the video id.
    """
    r = requests.get(f'https://youtube.com/watch?v={id}')
    r.raise_for_status()
    soup = BeautifulSoup(r.content, "lxml")
    return soup.title.string


if __name__ == '__main__':
    js = get_video_name("RJqimlFcJsM")
    print('\n\n')
    print(js)
Daniel Lee
  • 7,189
  • 2
  • 26
  • 44
0

I make a little bit of reinvention of excellent Porto's answer here, and wrote this snippet on Python:

import urllib, urllib.request, json

input = "C:\\urls.txt"
output = "C:\\tracks.csv"

urls=[line.strip() for line in open(input)]
for url in urls:
    ID = url.split('=')
    VideoID = ID[1]
    params = {"format": "json", "url": "https://www.youtube.com/watch?v=%s" % VideoID}
    url = "https://www.youtube.com/oembed"
    query_string = urllib.parse.urlencode(params)
    url = url + "?" + query_string
    with urllib.request.urlopen(url) as response:
        response_text = response.read()
        try:
            data = json.loads(response_text.decode())
        except ValueError as e:
            continue # skip faulty url
        if data is not None:
            author = data['author_name'].split(' - ')
            author = author[0].rstrip()
            f = open(output, "a", encoding='utf-8')
            print(author, ',', data['title'], sep="", file=f)

It eats a plain text file with Youtube URL list:

https://www.youtube.com/watch?v=F_Vfgdfgg
https://www.youtube.com/watch?v=RndfgdfN8
...

and returns a CSV file with Artist-Title pairs:

Beyonce,Pretty hurts
Justin Timberlake,Cry me a river
Suncatcher
  • 10,355
  • 10
  • 52
  • 90
0

There are two modules that can help you which is pafy & youtube-dl. First install this module using pip. Pafy is using youtube-dl in the background to fetch the video information, you can also download videos using pafy and youtube-dl.

pip install youtube_dl
pip install pafy

Now you need to follow this code, I assume that you have the URL of any youtube video.

import pafy

def fetch_yt_video(link):
    video = pafy.new(link)
    print('Video Title is: ',video.title)

fetch_yt_video('https://youtu.be/CLUsplI4xMU')

The output is

Video Title is:  Make the perfect resume | For freshers & experienced | Step by step tutorial with free format
Kushal Bhavsar
  • 388
  • 3
  • 6