【问题标题】:How to Youtube transcript with api (captions.download如何使用 api 制作 Youtube 成绩单 (captions.download
【发布时间】:2019-11-12 14:09:27
【问题描述】:

我已经构建了一个 javascript 代码,以便能够读取任何 Youtube 视频脚本 (gapi.client.youtube.captions.download)。 auth 2.0 工作正常,我在本地 Web 服务器上运行我的应用程序一切都很好,问题是当我运行请求时出现错误 403: cb=gapi.loaded_0:164 GET https://content.googleapis.com/youtube/v3/captions/My_API_Key 403 我还没有找到StackOverflow 中的任何解决方案.. 有什么想法吗?

这是我的 js 文件:

const CLIENT_ID = 'My_Client_ID';
const DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest"];
const SCOPES = 'https://www.googleapis.com/auth/youtube.readonly';

const authorizeButton = document.getElementById('enter-button');
const signoutButton = document.getElementById('exit-button');
const content = document.getElementById('content');

// default youtube channel
const defaultChannel = 'googledevelopers';

// Load auth2 library
function handleClientLoad(){
    gapi.load('client:auth2', initClient);
}

// Init API client library and set up sing in listeners
function initClient(){
    gapi.client.init({
        discoveryDocs: DISCOVERY_DOCS,
        clientId: CLIENT_ID,
        scope: SCOPES
    }).then(() => {
        // Listen for sing state changes
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
        // Handle initial sign in state
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
        authorizeButton.onclick = handleAuthClick;
        signoutButton.onclick = handleSignouClick;
    });
}

// update UI sign in state changes
function updateSigninStatus(isSignedIn){
    if(isSignedIn){
        authorizeButton.style.display = 'none';
        signoutButton.style.display = 'block';
        content.style.display = 'block';
        getChannel(defaultChannel);
    }else{
        authorizeButton.style.display = 'block';
        signoutButton.style.display = 'none';
        content.style.display = 'none';
    }
}

// Handle Login
function handleAuthClick(){
    gapi.auth2.getAuthInstance().signIn();
}

// Handle Logout
function handleSignouClick(){
    gapi.auth2.getAuthInstance().signOut();
}

// Display channel Data
function showChannelData(data){
    const channelData = document.getElementById('channel-data');
    channelData.innerHTML = data;
}

// Get channel from API
function getChannel(channel){
    gapi.client.youtube.captions.download({
        id: 'guMGyC1tUYAdL3hgBlcGnW4Rt_bBUbtp'
    })
    .then(response => {
        console.log(response);
        const channel = response.result.items[0];
    })
    .catch(err => alert('No Channel By THat Name'));
}

这是我的 index.ejs 文件:

<!DOCTYPE html>
<html lang="en">
    <head>      
        <title>Your awesome Youtube search engine</title>
        <meta charset="UTF-8" />                    
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="Awesome videos!" />
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    </head>
    <body>
        <header>
            <h1 class="w100 text-center"><a href="index.html">YouTube Viral Search</a></h1>
        </header>

<div class="container">
        <p>Login with Google</p>
        <button class="btn green" id="enter-button">Log In</button>
        <button class="btn green" id="exit-button">Log Out</button>
        <br />
        <div id="content">
            <div class="row">
                <div id="channel-data" class="col s12"></div>
            </div>
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-rc.2/js/materialize.min.js"></script>
<script src="/javascripts/appYT.js"></script>
    <script async defer src="https://apis.google.com/js/api.js"
      onload="this.onload=function(){};handleClientLoad()"
      onreadystatechange="if (this.readyState === 'complete') this.onload()">
    </script>
    </body>
</html>
enter code here

【问题讨论】:

  • 更多说明,这是我看到的错误消息:权限不足:请求的身份验证范围不足。我不明白!阅读任何 youtube 字幕轨道是公开的吗?我的身份验证工作正常
  • 莉迪亚,你有这个错误是单个视频还是任何视频?
  • 我有任何视频
  • 试试这个code 并进行测试。不能肯定地说为什么你有这样的错误。希望对您有所帮助,如果有帮助,请指出,我将其作为答案发布。
  • 好的,我试试。所以你没有为此使用gapi?

标签: javascript youtube google-apis-explorer google-api-js-client


【解决方案1】:

您可以使用以下代码获取给定视频中的脚本。

This is the working jsfiddle


注意这里我有videoId zenMEj0cAC4,但你可以随意更改它。

$.ajax({
  type: "GET",
  url: "https://video.google.com/timedtext?type=track&v=zenMEj0cAC4&id=0&lang=en",
  crossDomain: true,
}).done(function(data) {
  console.log(data);
  getCaption(data);
});


var parser, xmlDoc;
var HTML_captions = "";

// Parse the AJAX response and get the captions.
function getCaption(ajax_response) {
  try {

    parser = new DOMParser();
    xmlDoc = parser.parseFromString(ajax_response, "text/xml");
    //console.log(ajax_response);
    //console.log(xmlDoc.getElementsByTagName("transcript").length);

    if (xmlDoc.getElementsByTagName("transcript").length > 0) {
      // Loop the results of the xmlDoc:
      for (var i = 0; i < xmlDoc.getElementsByTagName("transcript")[0].childNodes.length; i++) {
        console.log(xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
        HTML_captions += xmlDoc.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
      }
    } else {
      // Loop the results of the ajax_response;
      for (var i = 0; i < ajax_response.getElementsByTagName("transcript")[0].childNodes.length; i++) {
        console.log(ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML);
        HTML_captions += ajax_response.getElementsByTagName("transcript")[0].childNodes[i].innerHTML + "<br/>";
      }
    }

    document.getElementById("demo").innerHTML = "<i>Preparing captions...</i>";
    setTimeout(fillData(), 2000);

  } catch (err) {
    console.log(err);
    document.getElementById("demo").innerHTML = ('Error at getCaption function - see console form more details.');
    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);
    document.getElementById("demo").innerHTML = ('Error at fillData function - see console form more details.');
    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 id="demo"><i>Loading captions...</i></div>

如果您需要更多关于如何获得自动隐藏字幕的信息,您可以参考 Stack Overflow 中的这些答案:

【讨论】:

  • @Lydiahalls,您必须“例如在 Google chrome 中”激活 F12 开发人员工具,然后在 YouTube 上播放视频,然后在按下激活按钮后检查“网络”选项卡视频上的字幕。您会在那里看到提出的请求。希望对您有所帮助。
  • 对于某些 YT 视频,“video.google.com/timedtext?v=...”和“youtube.com/api/timedtext?v=...”在 1-我查看网络选项卡时都不起作用那些网址? 2-如果我想使用另一种语言,例如可以将“&lang=en&name=CC%20(English)”更改为“&lang=fr&name=CC%20(French)”吗?我非常感谢您的帮助 Mauricio ;)
  • 它不适用于此视频,例如:youtube.com/watch?v=9Tl3OmwrSaM 3- 你知道为什么吗?谢谢:)
  • Mauricio 你是最棒的..现在我知道如何从 Network Tab 获得它了..非常感谢 :)
  • @LeeGee,在您提供的 videoId 中,答案为空。这可能是频道本身的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
相关资源
最近更新 更多