Get title from YouTube videos

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

Thanks.

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.

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

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

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.

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"
   }
  }
 ]
}

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?.

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"

// 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;

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})

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.

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.

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

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

Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();

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])
}

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

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('nn')
    print(js)

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

Leave a Comment