从YouTube视频中获取标题

9 浏览
0 Comments

从YouTube视频中获取标题

我想提取YouTube视频的标题。我该如何做?

谢谢。

admin 更改状态以发布 2023年5月21日
0
0 Comments

你好,在 python3 中我发现了两种方法

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': '',
 '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

0
0 Comments

我所知道的获取YouTube视频信息的最简单方法是解析从此处检索的字符串: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打印视频的标题。

0