从YouTube视频中获取标题
我想提取YouTube视频的标题。我该怎么做从YouTube视频中获取标题,youtube,Youtube,我想提取YouTube视频的标题。我该怎么做 谢谢。一种方法是从youtube检索视频,如图所示 然后从youtube发送的atom提要中提取标题。显示了一个示例提要获取youtube视频afaik信息的最简单方法是解析从以下位置检索到的字符串: 使用类似PHP的工具,您可以获得视频中几乎所有内容的良好阵列: $content = file_get_contents("http://youtube.com/get_video_info?video_id=".$id); parse_str($co
谢谢。一种方法是从youtube检索视频,如图所示
然后从youtube发送的atom提要中提取标题。显示了一个示例提要获取youtube视频afaik信息的最简单方法是解析从以下位置检索到的字符串: 使用类似PHP的工具,您可以获得视频中几乎所有内容的良好阵列:
$content = file_get_contents("http://youtube.com/get_video_info?video_id=".$id);
parse_str($content, $ytarr);
echo $ytarr['title'];
这将使用$id作为视频id打印视频标题。使用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"
#/bin/bash
阅读-e-p“Youtube地址?”地址
页面=$(wget“$地址”-O-2>/dev/null)
标题=$(回显“$page”| grep“-”)
title=“$(lynx--dump-force html使用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)
有关更多信息,请访问。如果您熟悉java,请尝试Jsoup解析器
Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();
我认为最好的方法是使用youTube的gdata,然后从返回的XML中获取信息
更新:
现在有一个更新的API,您应该改用它
下面是ColdFusion的一些剪切粘贴代码:
它使用YouTube API v3在CF9(可能还有更早的版本)上工作,这需要API密钥
我在其中留下了一些评论和诊断信息,供任何想深入挖掘的人使用。希望它能帮助别人。试试看,我正在播放列表中获取每个视频的名称和url,您可以根据需要修改此代码
$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])
}
您可以使用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'};
我希望它能解决您的问题。现在附带此功能。例如,显示视频的缩略图和标题是两行:
SS map = youtubeVideoInfo("https://www.youtube.com/watch?v=4If_vFZdFTk"));
showImage(map.get("title"), loadImage(map.get("thumbnail_url")));
如果喜欢python批处理脚本:我使用BeautifulSoup轻松解析HTML标题,urllib下载HTML和Unicodesv库,以保存Youtube标题中的所有字符
您需要做的唯一一件事是将带有单个(命名)列url的csv以及Youtube视频的url放置在与脚本相同的文件夹中,并将其命名为yt-url.csv并运行脚本。您将获得包含url及其标题的文件yt-url-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})
我将按照报告概述的流程进行规划
登录要与YouTube API使用关联的Google帐户
在创建一个新项目
- 在左上角的Google API徽标旁边,转到选择一个项目和创建项目+
- 等待创建完成
创建一个新的API密钥。您需要它来访问v3下的视频信息
- 如果您还不在,请转到左侧导航器下的凭据,API和服务>凭据
- 在凭据选项卡下,单击创建凭据,然后选择API密钥
- 将API密钥复制到剪贴板
提供视频ID和新创建的API密钥,请转到此链接以查看您的实际工作:https://www.googleapis.com/youtube/v3/videos?id=&key=%20&part=snippet
(无尖括号)
- 有关可访问内容的更多信息,请参见此处:。为方便起见,我将在此处复制其中一个示例(示例4)。URL中的
字段
和部分
参数在此处是关键参数
例子
URL
是您可以通过浏览器查看的URL。作为回报,您应该获得API响应下的内容:
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访问此信息,您可以下一步转到这里:。类似于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)
你好,在《蟒蛇3》中,我发现了两种方法
1)没有API密钥
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
{'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
示例结果:
{'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
{'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
使用python我得到了它import-pafy-url=”https://www.youtube.com/watch?v=bMt47wvK6u0“video=pafy.new(url)print(video.title)
我对Python做了一点重新设计,并在Python上编写了以下代码片段:
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
每次打开youtube时,视频标题下方都会显示一个标题。请看:这种方法非常方便。有关于这种方法的官方文档吗?谢谢。据我所知,这并不是最好的方法,因为获取视频信息可能会像获取视频一样消失eo提供了。但是,使用此方法,您可以访问官方API中未提供的一些信息(如下载Youtube视频的直接流URL,如get_video provided)。简短解决方案:如果官方Youtube API(如Alex.Bullard在此处回答)如果没有提供所需的信息,请尝试探测get_video_InfoThank@craul,这正是我需要的信息:)@black_belt我知道你的评论很老了,你现在可能已经意识到了这一点,但很可能OP不是为具有PHP访问权限的页面设计的。解析_str()之后,我们需要:$jsondec=json\u decode($ytarr['player_response'],true);echo$jsondec['videoDetails'][title];我已经编辑了答案。YouTube关闭了旧的API。在这里查看有关新版本的更多信息。我正在获取CORS…这对我来说非常有用。
Beyonce,Pretty hurts
Justin Timberlake,Cry me a river