我想提取YouTube视频的标题。我怎么能这样做?
感谢。
答案 0 :(得分:57)
获取有关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来打印视频的标题。
答案 1 :(得分:8)
答案 2 :(得分:7)
使用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上提供了更多信息。
答案 3 :(得分:5)
我认为最好的方法是使用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"
}
}
]
}
答案 4 :(得分:4)
用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"
答案 5 :(得分:4)
// 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;
答案 6 :(得分:2)
你好,我在 python3 中建立了2种方法
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
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
答案 7 :(得分:2)
如果感谢python批处理脚本:我使用 BeautifulSoup 轻松地从HTML解析标题, urllib 下载HTML和 unicodecsv 库以保存Youtube标题中的所有字符。
您唯一需要做的就是将带有单个(已命名)列网址的csv与Youtube视频的网址放在与脚本相同的文件夹中,并将其命名为 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})
答案 8 :(得分:2)
我将列出YouTube API v3 documentation概述的流程。
在https://console.developers.google.com/apis/credentials创建新项目。
制作新的API密钥。您需要它来访问v3下的视频信息。
https://www.googleapis.com/youtube/v3/videos?id=<YOUR VIDEO ID HERE>&key=<YOUR API KEY HERE>%20&part=snippet
(无尖括号)
fields
和part
参数是关键所在。 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?。
答案 9 :(得分:1)
以下是ColdFusion的一些剪切和粘贴代码:
http://trycf.com/gist/f296d14e456a7c925d23a1282daa0b90
适用于使用YouTube API v3的CF9(可能还有早期版本),需要API密钥。
对于想要深入挖掘的人,我留下了一些评论和诊断内容。希望它可以帮到某人。答案 10 :(得分:1)
您可以使用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'};
我希望它能解决你的问题。
答案 11 :(得分:0)
使用python我明白了import pafy url = "https://www.youtube.com/watch?v=bMt47wvK6u0" video = pafy.new(url) print(video.title)
答案 12 :(得分:0)
也可以通过使用scrapy模块完成
我只是告诉你cmd行
草皮外壳“ https://www.youtube.com/channel/UCVPrNa-6fkLu4DVF2m_0n2A”
或使用视频链接
然后输入
Out[1]: response.xpath("//h1/span/text()").getall()
Out[1]: ['\n Python Package Publishing (Part-2) | Setting up the Package\n ']
请记住,您需要安装scrapy模块
这是100%可行的方法,也是迄今为止我找到标题和所有其他描述的最简单的方法。
答案 13 :(得分:0)
与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)
答案 14 :(得分:0)
JavaX现在附带此功能。例如,显示视频的缩略图和标题是两行的:
SS map = youtubeVideoInfo("https://www.youtube.com/watch?v=4If_vFZdFTk"));
showImage(map.get("title"), loadImage(map.get("thumbnail_url")));
答案 15 :(得分:0)
试试这个,我在播放列表中获取每个视频的名称和网址,您可以根据自己的要求修改此代码。
$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])
}
答案 16 :(得分:0)
如果您熟悉java,请尝试使用Jsoup解析器。
Document document = Jsoup.connect("http://www.youtube.com/ABDCEF").get();
document.title();