【问题标题】:Retrieve YouTube Video title using API (Python)?使用 API (Python) 检索 YouTube 视频标题?
【发布时间】:2020-04-24 21:10:59
【问题描述】:

这两个输入应该有相同的标题:

https://www.youtube.com/watch?v=LAUa5RDUvO4

https://youtu.be/LAUa5RDUvO4

但我无法同时在一个程序中工作,似乎是因为找不到短网址的 ID(在这里,LAUa5RDUvO4)。

如何使用Youtube API 打印标题?

【问题讨论】:

  • 这能回答你的问题吗? Get title from YouTube videos
  • 欢迎来到stackoverflow。这不是免费的代码编写服务。它也不是教程或网络搜索的替代品。请阅读How to Ask。然后edit您的问题并添加您迄今为止尝试过的代码。当你运行它时会发生什么?你期望会发生什么?有什么错误吗?
  • 已编辑,抱歉。

标签: python youtube


【解决方案1】:

您可以使用此代码获取视频标题。您只需要视频ID。这个问题已经有了答案Get title from YouTube videos。希望问题被重复。下面的答案来自我觉得很有用的波尔图。

import urllib.request
import json
import urllib

#change to yours VideoID or change url inparams
VideoID = "LAUa5RDUvO4" 

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())
    print(data['title'])

【讨论】:

  • 感谢您的快速回复 - 但是,我运行了这个,它还打印了视频分辨率和视频规格。有没有办法只打印标题?
  • 现在你可以试试了。它只打印标题。
  • 非常感谢
【解决方案2】:

您可以使用 lxml 解析器和 xpath 表达式来提取 youtube 视频的标题

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

【讨论】:

  • 谢谢,我现在不打算使用 lxml 但这绝对有帮助!
猜你喜欢
  • 2014-09-02
  • 2016-03-05
  • 2013-07-18
  • 2020-07-07
  • 2018-10-27
  • 2013-04-20
  • 2022-01-12
  • 2012-10-10
  • 1970-01-01
相关资源
最近更新 更多