【问题标题】:Is it possible to retrieve the description of a youtube video without authenticating through the API?是否可以在不通过 API 进行身份验证的情况下检索 youtube 视频的描述?
【发布时间】:2017-02-05 14:01:35
【问题描述】:

我正在尝试编写一个 Greasemonkey 脚本来提取 Youtube 视频的描述并将其插入到另一个使用嵌入式视频的网站中。

我发现这样做的唯一方法是使用 API 调用视频的所有数据。我认为这是一种过于复杂的方法,所以我想创建一个不需要身份验证并且可以抓取描述的脚本。

有什么办法吗?

【问题讨论】:

    标签: javascript api youtube greasemonkey


    【解决方案1】:

    使用https://www.youtube.com/get_video_info 服务返回一个URLSearchParams-兼容&-分隔的各种视频参数字符串,包括title

    function getYoutubeVideoTitle(id, callback) {
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'https://www.youtube.com/get_video_info?video_id=' + id,
            onload: function(r) {
                var encoded = (r.responseText.match(/(^|&)title=(.*?)(&|$)/) || [])[2] || '';
                callback(decodeURIComponent(encoded.replace(/\+/g, ' ')));
            }
        });
    }
    

    getYoutubeVideoTitle('jE51HWPz1l8', function(title) {
        console.log(title);
    });
    

    Specsavers 锅炉广告 - 2017

    要获取对象中的所有参数,将响应按& 拆分,并将每个元素按= 拆分为键/值:

    function getYoutubeVideoData(id, callback) {
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'https://www.youtube.com/get_video_info?video_id=' + id,
            onload: function(response) {
                var data = {};
                response.responseText.split('&').forEach(function(param) {
                    param = param.split('=');
                    data[param[0]] = decodeURIComponent(param[1].replace(/\+/g, ' '));
                });
                callback(data);
            }
        }
    }
    

    注释。

    在现代浏览器中,URLSearchParams 提供了更方便的访问:

            onload: (r) => callback(new URLSearchParams(r.responseText).get('title'));
    

            onload: (r) => {
                var data = {};
                for (var entry of new URLSearchParams(r.responseText).entries())
                    data[entry[0]] = entry[1];
                callback(data);
            }
    

    代码假定响应中没有重复的键,这对于 get_video_info 服务是正确的。

    要在响应中获取视频下载链接和更多信息,请修改请求 URL:

        GM_xmlhttpRequest({
            method: 'GET',
            url: 'https://www.youtube.com/get_video_info?video_id=' + id +
                 '&hl=en_US&html5=1&el=embedded&eurl=' + encodeURIComponent(location.href),
    

    【讨论】:

    • 使用 URLSearchParams,然后我是否像往常一样使用 Greasemonkey 将响应定位在网页中我想要的位置?
    • URLSearchParams 只是升级手动字符串拆分的便利,与其他无关。
    猜你喜欢
    • 2018-05-10
    • 2014-04-29
    • 1970-01-01
    • 2019-03-30
    • 2015-10-02
    • 1970-01-01
    • 2022-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多