【问题标题】:Fetch youtube video title and category from url using youtube api v3使用 youtube api v3 从 url 获取 youtube 视频标题和类别
【发布时间】:2016-07-04 11:54:20
【问题描述】:

我是这方面的初学者!我想从 python 中的 Url 中获取 youtube 视频的标题以及它的类别。

import lxml
from lxml import etree
youtube = etree.HTML(urllib.urlopen("http://www.youtube.com/watch?v=KQEOBZLx-Z8").read())
video_title = youtube.xpath("//span[@id='eow-title']/@title")
print ''.join(video_title)

输出:“圣诞节的 12 天 - 圣诞颂歌”

我已尝试使用lxml 模块来获取标题,但它不适用于所有视频,我希望使用 youtube api v3。但是我该如何开始,我浏览了很多网站并试图寻求帮助,但我的控制台总是出错。我在https://console.developers.google.com 为我的项目创建了服务器密钥,我现在该怎么办?我浏览了官方页面,但不能理解太多。我应该从哪里开始?我还查看了其他几个 SO 问题,这些代码对我不起作用。

 import urllib
 import simplejson

 id = 'KQEOBZLx-Z8'
 url = 'http://gdata.youtube.com/feeds/api/videos/%s?alt=json&v=2' % id

 json = simplejson.load(urllib.urlopen(url))

 title = json['entry']['title']['$t']
 author = json['entry']['author'][0]['name']

 print "id:%s\nauthor:%s\ntitle:%s" % (id, author, title)  

我该怎么办?

【问题讨论】:

  • 这真的是你的钥匙吗?
  • @PadraicCunningham 哪一个?
  • id,你也知道有一个python api吗?
  • 第二个代码只是我从另一个 SO 问题中复制的内容,尽管我确实尝试打印 json 并且“条目”不是其中的一部分!如果可以的话,请帮忙!
  • @PadraicCunningham,我认为这是视频 ID。

标签: python youtube


【解决方案1】:

您可以使用google-api-client lib 访问数据,简单示例:

from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser

# Set DEVELOPER_KEY to the API key value from the APIs & auth > Registered apps
# tab of
#   https://cloud.google.com/console
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = key
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"


def youtube_search(vid):
    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                    developerKey=DEVELOPER_KEY)

    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = youtube.search().list(
    part="snippet",
    relatedToVideoId=vid,
    type="video",
).execute()
print(search_response)
    print(search_response)


try:
    youtube_search("KQEOBZLx-Z8")
except HttpError as  e:
    print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

有效参数在here 中列出,下面是另一个完整示例。您需要启用 youtube 数据 api 并拥有 开发者密钥。

使用请求:

import requests

url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={id}&key={api_key}"
_id = "KQEOBZLx-Z8"
r = requests.get(url.format(id=_id, api_key=DEVELOPER_KEY))

print(r.json())

这给了你:

{u'etag': u'"5g01s4-wS2b4VpScndqCYc5Y-8k/8KOFImC75qsfDbVWk53UnuxsQmo"',
 u'items': [{u'etag': u'"5g01s4-wS2b4VpScndqCYc5Y-8k/60ikaVqe2cge-D1XrdM2l0Bf4Jg"',
             u'id': u'KQEOBZLx-Z8',
             u'kind': u'youtube#video',
             u'snippet': {u'categoryId': u'1',
                          u'channelId': u'UC3djj8jS0370cu_ghKs_Ong',
                          u'channelTitle': u'HooplaKidz',
                          u'description': u'Check out http://vid.io/xovq for Non-Stop Children Songs!\nEveryone likes to enjoy festivals, so come and sing along to this beautiful 12 Days of Christmas which will be loved by one and all !!! \n\nLyrics to Sing Along :-\n-------------------------------------\nOn the first day of Christmas, \nmy true love sent to me \nA partridge in a pear tree.\n \nOn the second day of Christmas, \nmy true love sent to me \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the third day of Christmas, \nmy true love sent to me \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the fourth day of Christmas, \nmy true love sent to me \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the fifth day of Christmas, \nmy true love sent to me \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the sixth day of Christmas, \nmy true love sent to me \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the seventh day of Christmas, \nmy true love sent to me \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the eighth day of Christmas, \nmy true love sent to me \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the ninth day of Christmas, \nmy true love sent to me \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the tenth day of Christmas, \nmy true love sent to me \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the eleventh day of Christmas, \nmy true love sent to me \nEleven pipers piping, \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the twelfth day of Christmas, \nmy true love sent to me \nTwelve drummers drumming, \nEleven pipers piping, \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree!  \n\nDownload Hooplakidz Songs on iTunes:\nhttp://itunes.apple.com/us/album/hoopla-kidz/id439987868\n\nBecome a Hooplakidz Fan on Facebook:\nhttp://www.facebook.com/hooplakidz',
                          u'liveBroadcastContent': u'none',
                          u'localized': {u'description': u'Check out http://vid.io/xovq for Non-Stop Children Songs!\nEveryone likes to enjoy festivals, so come and sing along to this beautiful 12 Days of Christmas which will be loved by one and all !!! \n\nLyrics to Sing Along :-\n-------------------------------------\nOn the first day of Christmas, \nmy true love sent to me \nA partridge in a pear tree.\n \nOn the second day of Christmas, \nmy true love sent to me \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the third day of Christmas, \nmy true love sent to me \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the fourth day of Christmas, \nmy true love sent to me \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the fifth day of Christmas, \nmy true love sent to me \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the sixth day of Christmas, \nmy true love sent to me \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the seventh day of Christmas, \nmy true love sent to me \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the eighth day of Christmas, \nmy true love sent to me \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the ninth day of Christmas, \nmy true love sent to me \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the tenth day of Christmas, \nmy true love sent to me \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the eleventh day of Christmas, \nmy true love sent to me \nEleven pipers piping, \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree. \n\nOn the twelfth day of Christmas, \nmy true love sent to me \nTwelve drummers drumming, \nEleven pipers piping, \nTen lords a-leaping, \nNine ladies dancing, \nEight maids a-milking, \nSeven swans a-swimming, \nSix geese a-laying, \nFive golden rings, \nFour calling birds, \nThree French hens, \nTwo turtle doves, \nAnd a partridge in a pear tree!  \n\nDownload Hooplakidz Songs on iTunes:\nhttp://itunes.apple.com/us/album/hoopla-kidz/id439987868\n\nBecome a Hooplakidz Fan on Facebook:\nhttp://www.facebook.com/hooplakidz',
                                         u'title': u'12 Days of Christmas | Christmas Carols by Hooplakidz'},
                          u'publishedAt': u'2011-12-15T08:59:29.000Z',
                          u'tags': [u'12 days of christmas',
                                    u'Twelve Days Of Christmas (Holiday Period)',
                                    u'christmas carols',
                                    u'Christmas Carol (Composition Type)',
                                    u'christmas carols songs',
                                    u'christmas carols for children',
                                    u'christmas carols for kids',
                                    u'christmas songs',
                                    u'christmas songs for children',
                                    u'Christmas Music (Musical Genre)',
                                    u'Christmas (Holiday)',
                                    u'hooplakidz'],
                          u'thumbnails': {u'default': {u'height': 90,
                                                       u'url': u'https://i.ytimg.com/vi/KQEOBZLx-Z8/default.jpg',
                                                       u'width': 120},
                                          u'high': {u'height': 360,
                                                    u'url': u'https://i.ytimg.com/vi/KQEOBZLx-Z8/hqdefault.jpg',
                                                    u'width': 480},
                                          u'maxres': {u'height': 720,
                                                      u'url': u'https://i.ytimg.com/vi/KQEOBZLx-Z8/maxresdefault.jpg',
                                                      u'width': 1280},
                                          u'medium': {u'height': 180,
                                                      u'url': u'https://i.ytimg.com/vi/KQEOBZLx-Z8/mqdefault.jpg',
                                                      u'width': 320},
                                          u'standard': {u'height': 480,
                                                        u'url': u'https://i.ytimg.com/vi/KQEOBZLx-Z8/sddefault.jpg',
                                                        u'width': 640}},
                          u'title': u'12 Days of Christmas | Christmas Carols by Hooplakidz'}}],
 u'kind': u'youtube#videoListResponse',
 u'pageInfo': {u'resultsPerPage': 1, u'totalResults': 1}}

获取title和categoryId:

r = requests.get(url.format(id=_id, api_key=DEVELOPER_KEY))
js = r.json()
items = js["items"][0]
print (items["snippet"]["categoryId"])
print (items["snippet"]["title"])

输出:

1
12 Days of Christmas | Christmas Carols by Hooplakidz

这将允许您以编程方式完成所有操作,创建 id 到类别名称的映射:

import requests

def get_data(key, region, *ids):
    url = "https://www.googleapis.com/youtube/v3/videos?part=snippet&id={ids}&key={api_key}"
    r = requests.get(url.format(ids=",".join(ids), api_key=key))
    js = r.json()
    items = js["items"]
    cat_js = requests.get("https://www.googleapis.com/youtube/v3/videoCategories?part=snippet&regionCode={}&key={}".format(region,
        key)).json()
    categories = {d['id']: d["snippet"]['title'] for d in cat_js["items"]}
    for item in items:
        yield item["snippet"]["title"], categories[item["snippet"]["categoryId"]]

如果我们通过传入 he required args 来运行它,我们会得到:

In [86]: for title, cat in get_data(DEVELOPER_KEY, "IE",  "KQEOBZLx-Z8", "ALTc-Cqz650"):
   ....:         print(title, cat)
   ....:     
(u'12 Days of Christmas | Christmas Carols by Hooplakidz', u'Film & Animation')
(u'Conor Mcgregor Favorite to win Rematch against Nate Diaz,Lesnar on Drug addiction,Ali Funeral', u'Sports')

【讨论】:

  • 嘿,这似乎没有给出标题和流派。我之前尝试过类似的代码。它提供了一个充满无用信息的巨大列表。我应该如何获得它?另外,我看到您在 youtube_search("KQEOBZLx-Z8") 中使用了 ID 而不是 url。我怎样才能使用网址呢?
  • 它确实给出了标题,查看返回的 json。所有有效字段都在链接中,该页面上也有多个示例。你在 url 中有 id 为什么你不能使用它?
  • 我只想要使用 url youtube.com/watch?v=KQEOBZLx-Z8 或 id KQEOBZLx-Z8 运行的主 url 的名称。我怎么知道列表中的哪一个是那个。尝试打开网址。该列表是否还显示推荐的?
  • @Blabber,你真的看过我的回答吗?替代方案是重点
  • (Y) 太好了!再次感谢。
猜你喜欢
  • 2015-12-01
  • 2015-06-27
  • 2016-01-21
  • 2014-06-05
  • 2015-10-12
  • 2018-01-30
  • 2013-04-13
  • 2017-10-14
  • 2016-10-16
相关资源
最近更新 更多