我正在尝试编写一个Greasemonkey脚本来提取Youtube视频的描述,并将其插入到另一个使用嵌入式视频的站点中。
我发现这样做的唯一方法是使用API调用视频的所有数据。我认为这是一种过于复杂的方法,因此,我想创建一个不需要身份验证并且可以抓取描述的脚本。
有什么办法吗?
最佳答案
使用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 Boiler Advert - 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),
关于javascript - 是否可以在不通过API进行身份验证的情况下检索YouTube视频的描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42052944/