Get title from YouTube videos
Asked Answered
O

19

44

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

Thanks.

Overcautious answered 1/8, 2009 at 7:4 Comment(2)
every time when u open the youtube it shows a title below the title the video is embedOvercautious
See also: #2068844Schaaff
D
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.

Diuresis answered 1/3, 2011 at 8:6 Comment(12)
This method is very convenient. Is there any official documentation on this method? Thanks.Neoplatonism
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_infoDiuresis
helped me today :) +1Kalimantan
Returns 410 NoLongerAvailableException nowShiny
I just tried with one video ID and it still worked for me: 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.Diuresis
Worked for my Extension - Thank You!Enunciate
This should really be done over https://. They redirect you there anywaySecurity
@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.Booze
just after parse_str() we need : $jsondec = json_decode($ytarr['player_response'],true); echo $jsondec['videoDetails'][title]; I have edited the answer.Warmhearted
@SunilKumar what happened to your edit? Can't see it in the history either.Flaunty
@Flaunty I am not sure.Warmhearted
Is this out of date? That url now gives a 410, moved or deleted.Popover
D
16

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
Duffer answered 5/10, 2018 at 11:2 Comment(0)
E
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.

Exigible answered 31/7, 2012 at 13:15 Comment(1)
YouTube shut down the old APIs. Take a look here for more info about the new version developers.google.com/youtube/v3/getting-started.Exigible
A
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

Acrobatics answered 1/8, 2009 at 7:21 Comment(0)
S
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?.

Salicaceous answered 31/1, 2018 at 4:47 Comment(0)
O
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"
   }
  }
 ]
}
Oina answered 11/1, 2014 at 13:40 Comment(0)
F
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"
Fold answered 20/5, 2011 at 2:50 Comment(0)
O
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;
Outbreed answered 25/10, 2012 at 15:30 Comment(0)
W
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})
Winger answered 20/12, 2017 at 14:39 Comment(0)
B
3

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

youtube-dl --get-title https://www.youtube.com/watch?v=dQw4w9WgXcQ
Biernat answered 11/4, 2022 at 7:24 Comment(0)
D
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.

Dude answered 17/3, 2017 at 22:50 Comment(0)
I
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.

Iow answered 31/7, 2017 at 8:20 Comment(0)
S
1

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

Shuttle answered 27/10, 2020 at 7:19 Comment(0)
B
0

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

Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();
Blake answered 16/2, 2013 at 12:18 Comment(0)
S
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])
}
Slim answered 21/6, 2017 at 17:34 Comment(0)
S
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

Security answered 31/10, 2017 at 0:14 Comment(0)
C
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)
Cyder answered 9/7, 2018 at 15:46 Comment(0)
P
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
Psychiatry answered 24/12, 2020 at 11:14 Comment(0)
V
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
Vasiliu answered 17/11, 2021 at 4:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.