【问题标题】:Get Subtitles data of a Youtube video using api in nodejs在 nodejs 中使用 api 获取 Youtube 视频的字幕数据
【发布时间】:2019-02-18 03:14:58
【问题描述】:
【问题讨论】:
标签:
node.js
api
youtube
caption
subtitle
【解决方案1】:
除了使用 YouTube Data API - caption1 来检索视频的字幕,您还可以使用 AJAX 回调来获取字幕。
1如果你想使用 YouTube 数据 API 来查询字幕,我建议你 read the documentation carefully。
在本例中,AJAX 回调用于从给定的 YouTube 视频中检索字幕。
使用XML parser,前一个AJAX回调的响应在for循环中迭代以获取字幕:
// Ajax callback to the YouTube channel:
$.ajax({
type: "GET",
url: "http://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
crossDomain: true,
}).done(function(data) {
getCaption(data);
});
// Variables.
var parser, xmlDoc;
var HTML_captions = "";
// Parse the AJAX response and get the captions.
function getCaption(data) {
try {
// Loop the results of the ajax:
for (var i = 0; i < data.getElementsByTagName("transcript")[0].childNodes.length; i++) {
HTML_captions += data.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
}
// Preparing captions...
fillData();
} catch (err) {
console.log(err);
alert('Error at getCaption function - see console form more details.');
}
}
// Fill the data "captions" in a HTML "div" control.
function fillData() {
try {
document.getElementById("demo").innerHTML = HTML_captions;
} catch (err) {
console.log(err);
alert('Error at fillData function - see console form more details.');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<div class="infoVideo">
<span>These are the captions of the following YouTube video:</span>
<br/>
<span>Title: How Turbochargers Work</span>
<br/>
<span>URL: https://www.youtube.com/watch?v=zenMEj0cAC4</span>
</div>
<br/>
<div id="demo"><i>Loading captions...</i></div>