【问题标题】:Get title from YouTube videos从 YouTube 视频中获取标题
【发布时间】:2010-11-16 00:09:16
【问题描述】:

我想提取 YouTube 视频的标题。我该怎么做?

谢谢。

【问题讨论】:

标签: youtube


【解决方案1】:

获取有关 youtube 视频 afaik 信息的最简单方法是解析从以下位置检索到的字符串:http://youtube.com/get_video_info?video_id=XXXXXXXX

使用 PHP 的 parse_str() 之类的东西,您可以获得关于视频的几乎所有内容的漂亮数组:

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

这将使用 $id 作为视频的 ID 打印视频的标题。

【讨论】:

  • 这个方法很方便。有没有关于这种方法的官方文档?谢谢。
  • 据我所知,这让我相信它实际上可能不是 最好的 方法,因为 get_video_info 很可能会像 get_video 一样死掉做过。但是,使用此方法您可以访问官方 API 中未提供的一些信息(例如下载 Youtube 视频的直接流 URL,如提供的 get_video)。简短的解决方案:如果官方 Youtube API(如 Alex.Bullard 在这里回答)没有提供所需的信息,请尝试探测 get_video_info
  • 谢谢@Cruel,这正是我需要的信息:)
  • @black_belt 我知道您的评论已经很老了,您现在可能已经意识到这一点,但很可能 OP 没有为具有 PHP 访问权限的页面设计。
  • 在 parse_str() 之后我们需要: $jsondec = json_decode($ytarr['player_response'],true); echo $jsondec['videoDetails'][title];我已经编辑了答案。
【解决方案2】:

你好在 python3 我创建了 2 种方式

1) 没有 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'])

示例结果:

{'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) 使用 Google API - 需要 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'])

示例结果:

{'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

【讨论】:

    【解决方案3】:

    执行此操作的一种方法是从 youtube 检索视频,如图所示 here

    然后从 youtube 发送的 atom 提要中提取标题。示例提要显示为here

    【讨论】:

      【解决方案4】:

      使用 JavaScript 数据 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);
      };
      

      那么你只需拨打loadInfo(videoId)

      更多信息请访问API documentation

      【讨论】:

      【解决方案5】:

      我将按照YouTube API v3 documentation 概述的过程进行布局。

      1. 创建/登录到您希望与 YouTube API 使用相关联的 Google 帐户
      2. 创建一个新项目https://console.developers.google.com/apis/credentials

        • 在左上角的 Google API 徽标旁边,转至 Select a projectCreate project +
        • 等待片刻,让创作完成。
      3. 制作新的 API 密钥。您需要它来访问 v3 下的视频信息。

        • 如果您还没有,请转到左侧导航器下的凭据,API 和服务 > 凭据
        • 在凭据选项卡下,单击创建凭据,然后选择API 密钥
        • 将 API 密钥复制到剪贴板。
      4. 提供视频 ID 和您新创建的 API 密钥,转到此链接以查看您的实际工作:https://www.googleapis.com/youtube/v3/videos?id=&lt;YOUR VIDEO ID HERE&gt;&amp;key=&lt;YOUR API KEY HERE&gt;%20&amp;part=snippet(无尖括号)

      示例

      URL 是您可以通过浏览器访问的 URL 以查看它。作为回报,您应该得到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"
         }
        }
       ]
      }
      

      这将为您提供.json 文件格式的视频信息。如果您的项目要通过 JavaScript 访问此信息,您接下来可能会去这里:How to get JSON from URL in Javascript?

      【讨论】:

        【解决方案6】:

        我认为最好的方法是使用youTube的gdata,然后从返回的XML中获取信息

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

        更新: 现在有一个更新的 API,你应该改用它

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

        【讨论】:

          【解决方案7】:

          使用 bash、wget 和 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"
          

          【讨论】:

            【解决方案8】:
            // 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;
            

            【讨论】:

              【解决方案9】:

              如果赞赏python批处理脚本:我使用BeautifulSoup轻松从HTML解析标题,urllib下载HTML和unicodecsv库以保存 Youtube 标题中的所有字符。

              您唯一需要做的就是将带有 单(命名)列 url 的 csv 与 Youtube 视频的 URL 放在与脚本相同的文件夹中,并将其命名为 yt- urls.csv 并运行脚本。您将获得包含 URL 及其标题的文件 yt-urls-titles.csv

              #!/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})
              

              【讨论】:

                【解决方案10】:

                以下是 ColdFusion 的一些剪切和粘贴代码:

                http://trycf.com/gist/f296d14e456a7c925d23a1282daa0b90

                它使用 YouTube API v3 在 CF9(可能还有更早的版本)上运行,这需要 API 密钥。

                我在里面留下了一些 cmets 和 diag 的东西,供任何想要深入挖掘的人使用。希望它可以帮助某人。

                【讨论】:

                  【解决方案11】:

                  您可以使用 Json 获取有关视频的所有信息

                  $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'};
                  

                  希望它能解决你的问题。

                  【讨论】:

                    【解决方案12】:

                    用python我知道了import pafy url = "https://www.youtube.com/watch?v=bMt47wvK6u0" video = pafy.new(url) print(video.title)

                    【讨论】:

                      【解决方案13】:

                      如果您熟悉 java,请尝试使用 Jsoup 解析器。

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

                      【讨论】:

                        【解决方案14】:

                        试试这个,我正在获取播放列表中每个视频的名称和网址,您可以根据需要修改此代码。

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

                        【讨论】:

                          【解决方案15】:

                          JavaX 现在附带此功能。例如,显示视频的缩略图和标题是一个两行:

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

                          Example

                          【讨论】:

                            【解决方案16】:

                            类似于 Matej M,但更简单:

                            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)
                            

                            【讨论】:

                              【解决方案17】:

                              我对@9​​87654321@做了一点改造,并在Python上写了这个sn-p:

                              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)
                              

                              它吃一个带有 Youtube URL 列表的纯文本文件:

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

                              并返回一个包含艺术家-标题对的 CSV 文件:

                              Beyonce,Pretty hurts
                              Justin Timberlake,Cry me a river
                              

                              【讨论】:

                                【解决方案18】:

                                pafy 和 youtube-dl 有两个模块可以帮助您。首先使用 pip 安装这个模块。 Pafy 在后台使用 youtube-dl 获取视频信息,您也可以使用 pafy 和 youtube-dl 下载视频。

                                pip install youtube_dl
                                pip install pafy
                                

                                现在您需要遵循此代码,我假设您拥有任何 youtube 视频的 URL。

                                import pafy
                                
                                def fetch_yt_video(link):
                                    video = pafy.new(link)
                                    print('Video Title is: ',video.title)
                                
                                fetch_yt_video('https://youtu.be/CLUsplI4xMU')
                                

                                输出是

                                Video Title is:  Make the perfect resume | For freshers & experienced | Step by step tutorial with free format
                                

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2012-05-22
                                  • 1970-01-01
                                  • 2013-03-23
                                  • 2015-08-09
                                  • 1970-01-01
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多