Как найти айди видео на ютубе

Перейти к содержанию

На чтение 2 мин Опубликовано 17.08.2015

Здравствуйте !

Есть плагины с помощью которых можно добавить на сайт видео, и в основном в настройках таких плагинов нужно указывать ID видеозаписи. Это не единственный случай в котором вам понадобится id видео, случаев может быть много, как же узнать id видеозаписи ? Я решил посвятить данному вопросу целую статью, так как считаю что не мало людей задаются и будут задаваться данным вопросом.

Итак, приступим к делу, давайте узнаем id любого видео с сайта Ютуб.

— Зайдите на сайт YuoTube, выберите любое видео.

— Правой кнопкой мыши нажмите по Заголовку или по Обложке видео.

— В открывшемся окне нажмите — Скопировать ссылку.

скопировать видео-ссылку

— Скопированную ссылку вставьте к примеру в Блокнот на компьютере.

блокнот

— В конце ссылки будет располагаться id видео. ID видео состоит из 11 символов.

— Копируете id видео из ссылки и вставляете в нужное вам место.

Так же можно скопировать ID видео не уходя с сайта YuoTube.

— Откройте любое видео для просмотра.

— В верху страницы нажмите по поисковому окну браузера и скопируйте ID видео. (смотри фото)

id ссылка

На этом всё, как видите здесь всё просто, если у вас остались вопросы, тогда пишите мне в Обратную связь, либо оставьте комментарий к данной записи. Я всем отвечу !

До новых встреч на страницах САМСАЙ !

I am working in an android app which shows videos from a YouTube Channel.

I have the channel id and all other stuffs. But I need the video id to show the video in YouTube Player.

***eg. player.cueVideo("nCgQDjiotG0");***

When I go through the developer site again and again, I got this one -https://www.googleapis.com/youtube/v3/videos?part=id&chart=mostPopular&key={YOUR_API_KEY}

It is working perfectly returning the correct Video id to play. But I can’t done it with my Channel id (There is no option for passing channel ID as parameter).

The only one url which accept the channel ID and returns snippet is this one —

https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCxUtHtpGzd0bA5rYRY7h4VQ&q=PIVideoLibrary&type=channel&key={YOUR_API_KEY}

But the id it returning is not compatible with the above method. When I run it in the device it shows "Invalid Request" Here is screen shot which is the response of the above search request.The Screen shot

So this is my question.

How can we get video id of a video from a YouTube channel to show that
vedio in a youtube player integrated in the android app using YouTube
api v3

Thank You.

Late to the game here, but I’ve mashed up two excellent responses from mantish and j-w. First, the modified regex:

const youtube_regex = /^.*(youtu.be/|vi?/|u/w/|embed/|?vi?=|&vi?=)([^#&?]*).*/

Here’s the test code (I’ve added mantish’s original test cases to j-w’s nastier ones):

 var urls = [
      'http://www.youtube.com/watch?v=0zM3nApSvMg&feature=feedrec_grec_index',
      'http://www.youtube.com/user/IngridMichaelsonVEVO#p/a/u/1/QdK8U-VIH_o',
      'http://www.youtube.com/v/0zM3nApSvMg?fs=1&hl=en_US&rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg#t=0m10s',
      'http://www.youtube.com/embed/0zM3nApSvMg?rel=0',
      'http://www.youtube.com/watch?v=0zM3nApSvMg',
      'http://youtu.be/0zM3nApSvMg',
      '//www.youtube-nocookie.com/embed/up_lNV-yoK4?rel=0',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/user/SilkRoadTheatre#p/a/u/2/6dwqZw0j_jY',
      'http://youtu.be/6dwqZw0j_jY',
      'http://www.youtube.com/watch?v=6dwqZw0j_jY&feature=youtu.be',
      'http://youtu.be/afa-5HQHiAs',
      'http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo?rel=0',
      'http://www.youtube.com/watch?v=cKZDdG9FTKY&feature=channel',
      'http://www.youtube.com/watch?v=yZ-K7nCVnBI&playnext_from=TL&videos=osPknwzXEas&feature=sub',
      'http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I',
      'http://www.youtube.com/embed/nas1rJpm7wY?rel=0',
      'http://www.youtube.com/watch?v=peFZbP64dsU',
      'http://youtube.com/v/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/vi/dQw4w9WgXcQ?feature=youtube_gdata_player',
      'http://youtube.com/?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?v=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtube.com/watch?vi=dQw4w9WgXcQ&feature=youtube_gdata_player',
      'http://youtu.be/dQw4w9WgXcQ?feature=youtube_gdata_player'
  ];

  var failures = 0;
  urls.forEach(url => {
    const parsed = url.match(youtube_regex);
    if (parsed && parsed[2]) {
      console.log(parsed[2]);
    } else {
      failures++;
      console.error(url, parsed);
    }
  });
  if (failures) {
    console.error(failures, 'failed');
  }

Experimental version to handle the m.youtube urls mentioned in comments:

const youtube_regex = /^.*((m.)?youtu.be/|vi?/|u/w/|embed/|?vi?=|&vi?=)([^#&?]*).*/

It requires parsed[2] to be changed to parsed[3] in two places in the tests (which it then passes with m.youtube urls added to the tests). Let me know if you see problems.

ТЛ; др.

Соответствует всем URL-примерам по этому вопросу, а затем и некоторым.

let re = /^(https?://)?((www.)?(youtube(-nocookie)?|youtube.googleapis).com.*(v/|v=|vi=|vi/|e/|embed/|user/.*/u/d+/)|youtu.be/)([_0-9a-z-]+)/i;
let id = "https://www.youtube.com/watch?v=l-gQLqv9f4o".match(re)[7];

ID всегда будет в группе совпадений 7.

Живые примеры всех URL-адресов, которые я получил из ответов на этот вопрос: https://regexr.com/3u0d4

Полное объяснение:

Как много ответов/комментариев поднял, есть много форматов для URL видео YouTube. Даже несколько TLD, где они могут показаться «размещенными».

Вы можете посмотреть полный список вариантов, которые я проверял, перейдя по ссылке regexr выше.

Давайте разберем RegExp.

^ Зафиксируйте строку в начале строки. (https?://)? Факультативные протоколы http://или https://The ? делает предыдущий элемент необязательным, поэтому s и вся группа (все, что заключено в скобки) являются необязательными.

Хорошо, следующая часть — это главное. По сути, у нас есть два варианта: различные версии www.youtube.com/…[id] и сокращенная ссылка youtu.be/[id] версия.

(                                                  // Start a group which will match everything after the protocol and up to just before the video id.
  (www.)?                                         // Optional www.
  (youtube(-nocookie)?|youtube.googleapis)         // There are three domains where youtube videos can be accessed. This matches them.
  .com                                            // The .com at the end of the domain. 
  .*                                               // Match anything 
  (v/|v=|vi=|vi/|e/|embed/|user/.*/u/d+/) // These are all the things that can come right before the video id. The | character means OR so the first one in the "list" matches.
  |                                                // There is one more domain where you can get to youtube, it the link shortening url which is just followed by the video id. This OR separates all the stuff in this group and the link shortening url.
  youtu.be/                                      // The link shortening domain
)                                                  // End of group

Наконец, у нас есть группа для выбора идентификатора видео. Как минимум один символ, который является цифрой, буквой, подчеркиванием или тире.

([_0-9a-z-]+)

Вы можете узнать гораздо больше подробностей о каждой части регулярного выражения, перейдя по ссылке регулярного выражения и увидев, как каждая часть выражения совпадает с текстом в URL.

Learn how to get the ID of any YouTube video.

This article walks you through how to get the ID of any YouTube video.

How to get a YouTube video ID from a youtube.com page URL

You may be watching the video or just happened to visit a link to a video. The video ID will be located in the URL of the video page, right after the v= URL parameter.

In this case, the URL of the video is: https://www.youtube.com/watch?v=aqz-KE-bpKQ.
Therefore, the ID of the video is aqz-KE-bpKQ.

How to get a YouTube video ID from a youtu.be short URL

The youtu.be URLs are created by generating a URL intendend for sharing. They differ slightly from youtube.com URLs because there are no URL parameters. Instead, the video ID is part of the URL itself.

In this case, the URL of the video is: https://youtu.be/aqz-KE-bpKQ.
Therefore, the ID of the video is aqz-KE-bpKQ.

How to get a YouTube video ID from an embedded video player

The easiest method is to use the «Stats for nerds» option.

  1. Right click the embedded video player to present a menu.
  2. Select the «Stats for nerds» option in the menu.
  3. Note the «Video ID» property.

Feel free to test on this video player in the following link: http://codepen.io/anon/pen/qReQZL

Понравилась статья? Поделить с друзьями:
  • Как найти свойство экрана
  • Как найти свой голос для разговора
  • Если потерял айфон что делать как найти
  • Как правильно составить статью для газеты
  • Как найти козу скайрим