如何使用YouTube API获取随机YouTube视频?

时间:2021-04-12 18:57:08

I need a way of getting a completely random YouTube video. No restriction.

我需要一种获取完全随机的YouTube视频的方法。没有限制。

How can I do with with the YouTube API?

如何使用YouTube API?

** edit * OK as requested here is what i tried so far:

**编辑*确定这里要求的是我到目前为止尝试的:

1 - went through the api and examples at youtube dev site. http://www.youtube.com/dev/ no luck finding the correct api or a way of doing it there.

1 - 在youtube开发站点浏览了api和示例。 http://www.youtube.com/dev/没有运气找到正确的api或在那里做的方式。

2 - google search of course ;) got http://randomyoutubevideo.net/ but they only offer an api from THEM to use in between me and youtube. < this gives me hope that it IS actually possible to do this.

2 - 谷歌搜索当然;)得到http://randomyoutubevideo.net/但他们只提供从他们在我和youtube之间使用的API。 <这让我希望实际上可以做到这一点。< p>

3 - even checked the youtube app gallery http://youtube-gallery.appspot.com/ to see if anyone is doing it. and HOW.

3 - 甚至检查了youtube应用程序库http://youtube-gallery.appspot.com/,看看有没有人这样做。如何。

what i will also do is ask on the youtube discussion pages. perhaps someone there can help.

我还要做的是在youtube讨论页面上询问。也许有人可以提供帮助。

9 个解决方案

#1


4  

There appears to be no way to do this, however there are ways to approximate what you're looking for. See here for ideas.

似乎没有办法做到这一点,但有一些方法来估计你正在寻找的东西。请看这里的想法。

The basic ideas from those pages are to use the most recent uploads feed (if you don't care about when something was uploaded) or simply get a dump of ALL youtube videos and randomly select a URL from those.

这些页面的基本思想是使用最新的上传源(如果您不关心何时上传内容)或只是转储所有YouTube视频并随机选择这些视频中的URL。

To quote the youtube API guy in first link:

在第一个链接中引用youtube API的人:

As others have mentioned, we make any data dumps or the like available. All your interaction with YouTube needs to be done via the standard API.

正如其他人所提到的,我们可以提供任何数据转储等。您与YouTube的所有互动都需要通过标准API完成。

I can't say that I have enough of a background in statistics to suggest how you could retrieve a truly random sample of videos. I do think that going about it by attempting to generate 11 character YouTube video ids is probably the wrong approach, though—there are just too many non-existent video ids that you'll bump up against, and I don't think the best use of the API is to make requests that will return HTTP 404 responses X% of the time.

我不能说我有足够的统计背景来建议你如何检索真正随机的视频样本。我确实认为通过尝试生成11个字符的YouTube视频ID来实现它可能是错误的方法,但是有太多不存在的视频ID,你会碰到它,我认为不是最好的使用API​​是为了在X%的时间内发出将返回HTTP 404响应的请求。

You might have better luck just using the API to search for words or phrases that are picked at "random" and taking a sampling of the results. If you do that, you should think about what value to use for the orderby= URL parameter. The default ordering is "relevance", which will lead to the top results being the ones that our algorithms think are the most relevant to your search terms. This might skew your results if you always grab the first entry or the like. You could also order by "published" which will give you a reverse-chronological feed of videos.

使用API​​搜索“随机”选取的单词或短语并对结果进行抽样,您可能会有更好的运气。如果这样做,您应该考虑使用orderby = URL参数的值。默认排序是“相关性”,这将导致最佳结果是我们的算法认为与您的搜索字词最相关的结果。如果您总是抓住第一个条目或类似条件,这可能会扭曲您的结果。您也可以通过“已发布”订购,这将为您提供反向按时间顺序排列的视频。

Cheers, -Jeff Posnick, YouTube API Team as With regards to randomyoutubevideo.net, this is what the "About" page of that site has to say:

干杯,-Jeff Posnick,YouTube API团队关于randomyoutubevideo.net,这就是该网站的“关于”页面所说的:

So how can we provide truly random links to YouTube videos? It turns out that the YouTube programming interface (API) provides additional functions that allow the discovery of videos that are much more random. Using a number of tricks, combined with a little manipulation of the space-time frabric, we have managed to create a process that yiields truly random links to YouTube videos.

那么我们如何才能提供真正随机的YouTube视频链接?事实证明,YouTube编程界面(API)提供了额外的功能,可以发现更随机的视频。使用了许多技巧,结合对时空碎片的一点操作,我们设法创建了一个流程,可以真实地随机链接到YouTube视频。

The random YouTube function on this page currently uses a subset of the database. Over time we will expand this database and, depending on demand, may make it available free of charge via an API.

此页面上的随机YouTube功能当前使用数据库的子集。随着时间的推移,我们将扩展此数据库,并根据需求,可以通过API免费提供。

I understand this to mean that they have been pulling large lists of videos from the API and making a DB of them from which they randomly select.

我理解这意味着他们一直在从API中提取大量视频,并制作他们随机选择的数据库。

#2


16  

As the owner of http://www.youtuberandomvideo.com/ I just randomly generate a few characters then search for v= and it returns all videos that have a video ID that starts with .

作为http://www.youtuberandomvideo.com/的所有者,我只是随机生成一些字符,然后搜索v =并返回所有视频ID开头的视频。

Once I have the results I just randomly select different videos.

一旦我得到结果,我就随机选择不同的视频。

#3


3  

Step 1: Create API-Key

  1. Create a google-Account
  2. 创建一个谷歌帐户

  3. Visit: https://console.developers.google.com/
  4. Create a new project: Click on Create new Project in head-menu and give it a name
  5. 创建一个新项目:单击head-menu中的Create new Project并为其命名

  6. Now Activate the YoutTubeData API: Click it and enable it.
  7. 现在激活YoutTubeData API:单击它并启用它。

  8. Insert your Applications-Infos
  9. 插入您的Applications-Infos

  10. Click "create Credentials"
  11. 点击“创建凭据”

  12. Klick what do i need?
  13. Klick我需要什么?

  14. Note your API-Key
  15. 请注意您的API密钥

Now you can access the YouTube-API.

现在您可以访问YouTube-API。

Step 2: Use YouTube-API to crawl Videos

In this step we use the YouTube-API to get random VideoId's. With the following Code-Samples you will get 50 random Apis from the YouTube-Search. That's the maximum. You can store them in a DB or return a random ID directly.

在此步骤中,我们使用YouTube-API获取随机VideoId。使用以下代码示例,您将从YouTube搜索中获得50个随机Apis。这是最大的。您可以将它们存储在数据库中或直接返回随机ID。

Attention: There is a limit of 30,000 units/second/user and 1,000,000 per day.

注意:每天限制30,000单位/秒和每天1,000,000。

Codesamples


[C#-Example]

using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;

namespace YouTube
{
   class Program
   {
    private static Random random = new Random();

    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    static void Main(string[] args)
    {
        var count = 50;
        var API_KEY = "YOUR KEY";
        var q = RandomString(3);
        var url = "https://www.googleapis.com/youtube/v3/search?key=" + API_KEY + "&maxResults="+count+"&part=snippet&type=video&q=" +q;

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(url);
            dynamic jsonObject = JsonConvert.DeserializeObject(json);
            foreach (var line in jsonObject["items"])
            {
                Console.WriteLine(line["id"]["videoId"]);
                /*store your id*/
            }
            Console.Read();
        }
    }
}
}

[PHP-Example]

function crawlVideos($count = 50)
{
    $q = $this->generateRandomString(3);
    $url = "https://www.googleapis.com/youtube/v3/search?key=" . self::API_KEY . "&maxResults=$count&part=snippet&type=video&q=" . $q;
    $JSON = file_get_contents($url);
    $JSON_Data_search = json_decode($JSON);
    foreach ($JSON_Data_search->{"items"} as $result) {
        $videoId = ($result->{"id"}->{"videoId"});
        /*Insert video to your database*/
    }
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

[Python-Example]

import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids

Step 3: Generate/Return your Video-URL

Now read a random ID from database like:

现在从数据库中读取一个随机ID,如:

SELECT 'id' 
FROM yttable
WHERE 1 ORDER BY RAND() LIMIT 1

Your random video is:

你的随机视频是:

https://www.youtube.com/embed/[random ID]

Have fun!

#4


1  

The best way to get random video IDs is to generate your own Database. Use the VideoSearch-Request of Google's Youtube-API. Just generate a searchquery like "v=SEARCH_STRING" and insert the videoids you get into your Database. The searchstring should be a randomly generated string. I found out, that a lenght of the string should be 4 chars to get most Videos out of a Request without having to many repeating Results.

获取随机视频ID的最佳方法是生成自己的数据库。使用Google的Youtube-API的VideoSearch-Request。只需生成类似“v = SEARCH_STRING”的搜索查询,然后将您获得的视频插入数据库。 searchstring应该是一个随机生成的字符串。我发现,字符串的长度应为4个字符,以便从请求中获取大多数视频而无需重复多次结果。

If your Database is ready, you can just get a random row out of it.

如果您的数据库已准备好,您可以随机获取一行。

I've done this on my own Website(random-video.net) and got over 2 million entrys in a few hours. There are no real limitations-just the size of your Database.

我已经在自己的网站(random-video.net)上完成了这项工作,并在几个小时内完成了200多万次。没有实际限制 - 只是数据库的大小。

#5


1  

Is a dirty crawler an option? Because I've used a simple random youtube vid link generator. It was only for accumulating a big db of videos, not for production.
It seems to be (very) similar to "youtuberandomvideo.com" approach as he described.

脏爬虫是一个选择吗?因为我使用了一个简单的随机youtube vid链接生成器。这只是为了积累大量的视频,而不是用于制作。它似乎(非常)类似于他描述的“youtuberandomvideo.com”方法。

import re, urllib
from random import randint

def random_str(str_size):
    res = ""
    for i in xrange(str_size):
        x = randint(0,25)
        c = chr(ord('a')+x)
        res += c
    return res

def find_watch(text,pos):
    start = text.find("watch?v=",pos)
    if (start<0):
        return None,None
    end = text.find(" ",start)
    if (end<0):
        return None,None

    if (end-start > 200): #silly heuristics, probably not a must
        return None,None

    return text[start:end-1], start


def find_instance_links():
    base_url = 'https://www.youtube.com/results?search_query='
    url = base_url+random_str(3)
    #print url

    r = urllib.urlopen(url).read()

    links = {}

    pos = 0
    while True:
        link,pos =  find_watch(r,pos)
        if link == None or pos == None:
            break
        pos += 1
        #print link
        if (";" in link):
            continue
        links[link] = 1

    items_list = links.items()

    list_size = len(items_list)
    selected = randint(list_size/2,list_size-1)
    return items_list[selected][0]


for i in xrange(1000):
    link = find_instance_links()
    print link

As you can see it's fairly simplistic and could probably break easily, but IIRC I managed to quickly get thousands of random video links which was all that I needed, and it's only few lines of code...

你可以看到它相当简单,可能很容易破解,但IIRC我设法迅速获得了数以千计的随机视频链接,这就是我所需要的,而且它只有几行代码......

Some explanation of the code: (random->pseudo random ...)
1. Random generation of search queries (3 letters long here)
2. Randomly selecting some link from the bottom half of the video links (the motivation was to avoid commercials)

代码的一些解释:(随机 - >伪随机...)1。随机生成搜索查询(这里长3个字母)2。从视频链接的下半部分随机选择一些链接(动机是为了避免广告)

Note:The code is messy - it should only serve as a basic example of the technique, not of proper code design and/or elegant python code.

注意:代码很乱 - 它应该只作为技术的基本示例,而不是正确的代码设计和/或优雅的python代码。

#6


1  

AFAIK: Searching for v= has no meaningful effect. iI you search for v=LadyGaga, you'll find Lady Gaga videos. YouTube's search algorithm looks through description, title, etc. - if a video has another video linked in its description (aka a ?v=..), it is more likely to come up with this search request. Also see https://developers.google.com/youtube/v3/docs/search/list .

AFAIK:搜索v =没有任何有意义的影响。如果你搜索v = LadyGaga,你会发现Lady Gaga的视频。 YouTube的搜索算法通过描述,标题等进行查看 - 如果视频在其描述中链接了另一个视频(也称为?v = ..),则更有可能提出此搜索请求。另请参阅https://developers.google.com/youtube/v3/docs/search/list。

There is no random pick implemented yet in Google's Youtube Data API. What I did was querying

谷歌的Youtube Data API中还没有随机选择。我做的是查询

https://www.googleapis.com/youtube/v3/search?part=id&maxResults=50&type=video&q=QUERYSTRING&key=KEY

, with QUERYSTRING being a random 5-character string in video-ID syntax. If the result set contains between 1 and 50 videos, of which at least one id contains the string, a random video was found. This method usually takes 1-5 tries.

,QUERYSTRING是视频ID语法中的随机5字符字符串。如果结果集包含1到50个视频,其中至少有一个id包含该字符串,则会找到随机视频。此方法通常需要1-5次尝试。

The last check is needed. Example: A random string was ydoat. Querying this with the above url results in only one video with the id VEBt0Hxp5Q8, which does not fit. The video probably contains the string in its description somewhere. If I search for ydoat via https://www.youtube.com/results?q=ydoat, no result is found. Searching for v%3Dydoat (v=ydoat) leads to the same results.

需要进行最后一次检查。示例:随机字符串是ydoat。使用上面的url查询此结果只会导致一个ID为VEBt0Hxp5Q8但不适合的视频。视频可能在某处包含其描述中的字符串。如果我通过https://www.youtube.com/results?q=ydoat搜索ydoat,则找不到任何结果。搜索v%3Dydoat(v = ydoat)会得到相同的结果。

See it in action @ http://cor-forum.de/randomtube/

在行动中查看它@ http://cor-forum.de/randomtube/

edit. source in php: https://github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

编辑。 php中的源代码:https://github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

Like Anton, I found 4 random characters will be best fitting.

像安东一样,我发现4个随机字符最合适。

#7


1  

I know it's a little bit off-topic but I can offer the following bash script. I use it on my Raspberry Pi and it works quite well.

我知道它有点偏离主题,但我可以提供以下bash脚本。我在我的Raspberry Pi上使用它并且效果很好。

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-5};echo)
    echo "$rand"
    searchresult=$(googler -C -n 100 --np -x -w https://www.youtube.com "$rand")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Prerequisites are that you have installed googler and youtube-dl. My initial idea was to generate random 11 character strings and to append them to the base URL for YouTube videos. However, the number of possible permutations is enormous (26 capital letters + 26 small letters + 10 digits + hyphen + underscore = 64 characters; 64^11=7.38x10^19 permutations) and will be used up if every person on the Earth uploads 10 billion videos. That's why randomly generating the complete 11-character identifier is not a practicable approach. My script generates random 5-character strings instead (variable "rand") and passes them as a search query to googler. Googler searches the YouTube site for these random strings and in most cases it returns results (variable "searchresult"). In case there is no result, the search is repeated with another random string and so on till success. Usually it takes one to three tries. I tried with different lengths of the search string - 4 is maybe not unique enough and 6 is too long and it can take a lot of tries to get a result and I observed that if the script sends more than 10 search requests in short time, Google temporarily blocks me from further searches.

先决条件是你已经安装了googler和youtube-dl。我最初的想法是生成随机的11个字符串,并将它们附加到YouTube视频的基本URL。然而,可能的排列数量是巨大的(26个大写字母+ 26个小写字母+10个数字+连字符+下划线= 64个字符; 64 ^ 11 = 7.38x10 ^ 19个排列)并且如果地球上的每个人上传都会用完100亿个视频。这就是为什么随机生成完整的11个字符的标识符不是一个切实可行的方法。我的脚本生成随机的5个字符的字符串(变量“rand”)并将它们作为搜索查询传递给googler。谷歌搜索YouTube网站上的这些随机字符串,在大多数情况下,它会返回结果(变量“searchresult”)。如果没有结果,则用另一个随机字符串重复搜索,依此类推,直到成功为止。通常需要一到三次尝试。我尝试使用不同长度的搜索字符串--4可能不够独特且6太长并且可能需要大量尝试才能得到结果我观察到如果脚本在短时间内发送超过10个搜索请求,谷歌暂时阻止我进一步搜索。

In the next step, the script extracts the hyperlinks to the YouTube videos from the search results and puts them in the variable "urls". Then one of them is randomly selected to be played (variable "url") and passed to the player - omxplayer in my case, but you can replace it with whichever player you want. Omxplayer is nice on the Raspberry Pi because it uses the hardware acceleration and outputs via hdmi directly to my TV set. If I change "-o hdmi" to "-o local" the audio is sent via the 3.5 mm stereo jack to an external amplifier. Pressing "q" during play stops playing the current video and the next random one starts automatically. It will go on forever till you press Ctrl-C to stop the script.

在下一步中,脚本会从搜索结果中提取指向YouTube视频的超链接,并将它们放入变量“urls”中。然后随机选择其中一个进行播放(变量“url”)并传递给播放器 - 在我的情况下为omxplayer,但你可以用你想要的任何一个播放器替换它。 Omxplayer在Raspberry Pi上很不错,因为它使用硬件加速并通过hdmi直接输出到我的电视机。如果我将“-o hdmi”更改为“-o local”,音频将通过3.5 mm立体声插孔发送到外部放大器。在播放期间按“q”将停止播放当前视频,下一个随机视频将自动开始播放。它会一直持续到你按Ctrl-C来停止脚本。

Additional tips

With some modifications you can get random videos on a given topic. For example, if we put "Deep Purple" as an additional search term we'll get random music videos by Deep Purple:

通过一些修改,您可以获得给定主题的随机视频。例如,如果我们将“Deep Purple”作为附加搜索词,我们将获得Deep Purple的随机音乐视频:

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-2};echo)
    echo "$rand"
    searchresult=$(googler -C -n 10 --np -x -w https://www.youtube.com "$rand" "Deep Purple")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Note that in the last example I have reduced the randomness factor to a 2-character string because it will be difficult to find a match for a 5-character string in the relatively small subset of all YouTube videos that contain the search term "Deep Purple". Also here I have limited the number of returned search results by googler to 10 to keep them relevant. With 100 I would also get less relevant results like videos of amateurs trying to play songs by Deep Purple.

请注意,在最后一个示例中,我将随机因子减少为2个字符的字符串,因为在包含搜索词“Deep Purple”的所有YouTube视频的相对较小的子集中,很难找到5个字符的字符串匹配项”。此外,我还将googler返回的搜索结果数量限制为10以保持相关性。有100个我也会得到不太相关的结果,如业余爱好者试图播放Deep Purple的歌曲。

The next script will play randomly only new videos that have been uploaded within the last 12 hours:

下一个脚本将仅随机播放过去12小时内上传的新视频:

    #!/bin/sh
    while [ true ];
    do
    searchresult=$(googler -C -n 100 --np -t h12 -x -w https://www.youtube.com "")
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

You can set different time constraints. See the documentation of googler for more details.

您可以设置不同的时间限制。有关更多详细信息,请参阅googler的文档。

#8


0  

Get a list of words, with hundreds or thousands of words. Then randomly select 2 words from it and use it as a query. This can also be useful if you want to have certain control of how random it could be. For instance you can have a list of english words, or a list of german words. Or have a smaller curated list with words only relevant to a topic you're interested in.

获取包含数百或数千个单词的单词列表。然后从中随机选择2个单词并将其用作查询。如果您想要对其随机性进行一定的控制,这也很有用。例如,您可以拥有英语单词列表或德语单词列表。或者有一个较小的策划列表,其中的单词仅与您感兴趣的主题相关。

#9


-1  

I coded a Python script using YouTube Data API v3. Generally, it is finding random videos according to a small keyword trick. For example, when you take a video, your phone will save it like "IMG 20180815", so search for these default filenames (IMG XXXX-XX-XX), take the ID of one of the randomly selected search result, then you have a random and unseen video.

我使用YouTube Data API v3编写了一个Python脚本。一般来说,它是根据一个小的关键字技巧找到随机视频。例如,当您拍摄视频时,您的手机会将其保存为“IMG 20180815”,因此搜索这些默认文件名(IMG XXXX-XX-XX),获取随机选择的搜索结果之一的ID,然后您拥有随机和看不见的视频。

https://github.com/n1rv4n4/random-youtube-video-generator

Example project website: https://www.randomyoutubevideo.com

示例项目网站:https://www.randomyoutubevideo.com

#1


4  

There appears to be no way to do this, however there are ways to approximate what you're looking for. See here for ideas.

似乎没有办法做到这一点,但有一些方法来估计你正在寻找的东西。请看这里的想法。

The basic ideas from those pages are to use the most recent uploads feed (if you don't care about when something was uploaded) or simply get a dump of ALL youtube videos and randomly select a URL from those.

这些页面的基本思想是使用最新的上传源(如果您不关心何时上传内容)或只是转储所有YouTube视频并随机选择这些视频中的URL。

To quote the youtube API guy in first link:

在第一个链接中引用youtube API的人:

As others have mentioned, we make any data dumps or the like available. All your interaction with YouTube needs to be done via the standard API.

正如其他人所提到的,我们可以提供任何数据转储等。您与YouTube的所有互动都需要通过标准API完成。

I can't say that I have enough of a background in statistics to suggest how you could retrieve a truly random sample of videos. I do think that going about it by attempting to generate 11 character YouTube video ids is probably the wrong approach, though—there are just too many non-existent video ids that you'll bump up against, and I don't think the best use of the API is to make requests that will return HTTP 404 responses X% of the time.

我不能说我有足够的统计背景来建议你如何检索真正随机的视频样本。我确实认为通过尝试生成11个字符的YouTube视频ID来实现它可能是错误的方法,但是有太多不存在的视频ID,你会碰到它,我认为不是最好的使用API​​是为了在X%的时间内发出将返回HTTP 404响应的请求。

You might have better luck just using the API to search for words or phrases that are picked at "random" and taking a sampling of the results. If you do that, you should think about what value to use for the orderby= URL parameter. The default ordering is "relevance", which will lead to the top results being the ones that our algorithms think are the most relevant to your search terms. This might skew your results if you always grab the first entry or the like. You could also order by "published" which will give you a reverse-chronological feed of videos.

使用API​​搜索“随机”选取的单词或短语并对结果进行抽样,您可能会有更好的运气。如果这样做,您应该考虑使用orderby = URL参数的值。默认排序是“相关性”,这将导致最佳结果是我们的算法认为与您的搜索字词最相关的结果。如果您总是抓住第一个条目或类似条件,这可能会扭曲您的结果。您也可以通过“已发布”订购,这将为您提供反向按时间顺序排列的视频。

Cheers, -Jeff Posnick, YouTube API Team as With regards to randomyoutubevideo.net, this is what the "About" page of that site has to say:

干杯,-Jeff Posnick,YouTube API团队关于randomyoutubevideo.net,这就是该网站的“关于”页面所说的:

So how can we provide truly random links to YouTube videos? It turns out that the YouTube programming interface (API) provides additional functions that allow the discovery of videos that are much more random. Using a number of tricks, combined with a little manipulation of the space-time frabric, we have managed to create a process that yiields truly random links to YouTube videos.

那么我们如何才能提供真正随机的YouTube视频链接?事实证明,YouTube编程界面(API)提供了额外的功能,可以发现更随机的视频。使用了许多技巧,结合对时空碎片的一点操作,我们设法创建了一个流程,可以真实地随机链接到YouTube视频。

The random YouTube function on this page currently uses a subset of the database. Over time we will expand this database and, depending on demand, may make it available free of charge via an API.

此页面上的随机YouTube功能当前使用数据库的子集。随着时间的推移,我们将扩展此数据库,并根据需求,可以通过API免费提供。

I understand this to mean that they have been pulling large lists of videos from the API and making a DB of them from which they randomly select.

我理解这意味着他们一直在从API中提取大量视频,并制作他们随机选择的数据库。

#2


16  

As the owner of http://www.youtuberandomvideo.com/ I just randomly generate a few characters then search for v= and it returns all videos that have a video ID that starts with .

作为http://www.youtuberandomvideo.com/的所有者,我只是随机生成一些字符,然后搜索v =并返回所有视频ID开头的视频。

Once I have the results I just randomly select different videos.

一旦我得到结果,我就随机选择不同的视频。

#3


3  

Step 1: Create API-Key

  1. Create a google-Account
  2. 创建一个谷歌帐户

  3. Visit: https://console.developers.google.com/
  4. Create a new project: Click on Create new Project in head-menu and give it a name
  5. 创建一个新项目:单击head-menu中的Create new Project并为其命名

  6. Now Activate the YoutTubeData API: Click it and enable it.
  7. 现在激活YoutTubeData API:单击它并启用它。

  8. Insert your Applications-Infos
  9. 插入您的Applications-Infos

  10. Click "create Credentials"
  11. 点击“创建凭据”

  12. Klick what do i need?
  13. Klick我需要什么?

  14. Note your API-Key
  15. 请注意您的API密钥

Now you can access the YouTube-API.

现在您可以访问YouTube-API。

Step 2: Use YouTube-API to crawl Videos

In this step we use the YouTube-API to get random VideoId's. With the following Code-Samples you will get 50 random Apis from the YouTube-Search. That's the maximum. You can store them in a DB or return a random ID directly.

在此步骤中,我们使用YouTube-API获取随机VideoId。使用以下代码示例,您将从YouTube搜索中获得50个随机Apis。这是最大的。您可以将它们存储在数据库中或直接返回随机ID。

Attention: There is a limit of 30,000 units/second/user and 1,000,000 per day.

注意:每天限制30,000单位/秒和每天1,000,000。

Codesamples


[C#-Example]

using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;

namespace YouTube
{
   class Program
   {
    private static Random random = new Random();

    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    static void Main(string[] args)
    {
        var count = 50;
        var API_KEY = "YOUR KEY";
        var q = RandomString(3);
        var url = "https://www.googleapis.com/youtube/v3/search?key=" + API_KEY + "&maxResults="+count+"&part=snippet&type=video&q=" +q;

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(url);
            dynamic jsonObject = JsonConvert.DeserializeObject(json);
            foreach (var line in jsonObject["items"])
            {
                Console.WriteLine(line["id"]["videoId"]);
                /*store your id*/
            }
            Console.Read();
        }
    }
}
}

[PHP-Example]

function crawlVideos($count = 50)
{
    $q = $this->generateRandomString(3);
    $url = "https://www.googleapis.com/youtube/v3/search?key=" . self::API_KEY . "&maxResults=$count&part=snippet&type=video&q=" . $q;
    $JSON = file_get_contents($url);
    $JSON_Data_search = json_decode($JSON);
    foreach ($JSON_Data_search->{"items"} as $result) {
        $videoId = ($result->{"id"}->{"videoId"});
        /*Insert video to your database*/
    }
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

[Python-Example]

import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids

Step 3: Generate/Return your Video-URL

Now read a random ID from database like:

现在从数据库中读取一个随机ID,如:

SELECT 'id' 
FROM yttable
WHERE 1 ORDER BY RAND() LIMIT 1

Your random video is:

你的随机视频是:

https://www.youtube.com/embed/[random ID]

Have fun!

#4


1  

The best way to get random video IDs is to generate your own Database. Use the VideoSearch-Request of Google's Youtube-API. Just generate a searchquery like "v=SEARCH_STRING" and insert the videoids you get into your Database. The searchstring should be a randomly generated string. I found out, that a lenght of the string should be 4 chars to get most Videos out of a Request without having to many repeating Results.

获取随机视频ID的最佳方法是生成自己的数据库。使用Google的Youtube-API的VideoSearch-Request。只需生成类似“v = SEARCH_STRING”的搜索查询,然后将您获得的视频插入数据库。 searchstring应该是一个随机生成的字符串。我发现,字符串的长度应为4个字符,以便从请求中获取大多数视频而无需重复多次结果。

If your Database is ready, you can just get a random row out of it.

如果您的数据库已准备好,您可以随机获取一行。

I've done this on my own Website(random-video.net) and got over 2 million entrys in a few hours. There are no real limitations-just the size of your Database.

我已经在自己的网站(random-video.net)上完成了这项工作,并在几个小时内完成了200多万次。没有实际限制 - 只是数据库的大小。

#5


1  

Is a dirty crawler an option? Because I've used a simple random youtube vid link generator. It was only for accumulating a big db of videos, not for production.
It seems to be (very) similar to "youtuberandomvideo.com" approach as he described.

脏爬虫是一个选择吗?因为我使用了一个简单的随机youtube vid链接生成器。这只是为了积累大量的视频,而不是用于制作。它似乎(非常)类似于他描述的“youtuberandomvideo.com”方法。

import re, urllib
from random import randint

def random_str(str_size):
    res = ""
    for i in xrange(str_size):
        x = randint(0,25)
        c = chr(ord('a')+x)
        res += c
    return res

def find_watch(text,pos):
    start = text.find("watch?v=",pos)
    if (start<0):
        return None,None
    end = text.find(" ",start)
    if (end<0):
        return None,None

    if (end-start > 200): #silly heuristics, probably not a must
        return None,None

    return text[start:end-1], start


def find_instance_links():
    base_url = 'https://www.youtube.com/results?search_query='
    url = base_url+random_str(3)
    #print url

    r = urllib.urlopen(url).read()

    links = {}

    pos = 0
    while True:
        link,pos =  find_watch(r,pos)
        if link == None or pos == None:
            break
        pos += 1
        #print link
        if (";" in link):
            continue
        links[link] = 1

    items_list = links.items()

    list_size = len(items_list)
    selected = randint(list_size/2,list_size-1)
    return items_list[selected][0]


for i in xrange(1000):
    link = find_instance_links()
    print link

As you can see it's fairly simplistic and could probably break easily, but IIRC I managed to quickly get thousands of random video links which was all that I needed, and it's only few lines of code...

你可以看到它相当简单,可能很容易破解,但IIRC我设法迅速获得了数以千计的随机视频链接,这就是我所需要的,而且它只有几行代码......

Some explanation of the code: (random->pseudo random ...)
1. Random generation of search queries (3 letters long here)
2. Randomly selecting some link from the bottom half of the video links (the motivation was to avoid commercials)

代码的一些解释:(随机 - >伪随机...)1。随机生成搜索查询(这里长3个字母)2。从视频链接的下半部分随机选择一些链接(动机是为了避免广告)

Note:The code is messy - it should only serve as a basic example of the technique, not of proper code design and/or elegant python code.

注意:代码很乱 - 它应该只作为技术的基本示例,而不是正确的代码设计和/或优雅的python代码。

#6


1  

AFAIK: Searching for v= has no meaningful effect. iI you search for v=LadyGaga, you'll find Lady Gaga videos. YouTube's search algorithm looks through description, title, etc. - if a video has another video linked in its description (aka a ?v=..), it is more likely to come up with this search request. Also see https://developers.google.com/youtube/v3/docs/search/list .

AFAIK:搜索v =没有任何有意义的影响。如果你搜索v = LadyGaga,你会发现Lady Gaga的视频。 YouTube的搜索算法通过描述,标题等进行查看 - 如果视频在其描述中链接了另一个视频(也称为?v = ..),则更有可能提出此搜索请求。另请参阅https://developers.google.com/youtube/v3/docs/search/list。

There is no random pick implemented yet in Google's Youtube Data API. What I did was querying

谷歌的Youtube Data API中还没有随机选择。我做的是查询

https://www.googleapis.com/youtube/v3/search?part=id&maxResults=50&type=video&q=QUERYSTRING&key=KEY

, with QUERYSTRING being a random 5-character string in video-ID syntax. If the result set contains between 1 and 50 videos, of which at least one id contains the string, a random video was found. This method usually takes 1-5 tries.

,QUERYSTRING是视频ID语法中的随机5字符字符串。如果结果集包含1到50个视频,其中至少有一个id包含该字符串,则会找到随机视频。此方法通常需要1-5次尝试。

The last check is needed. Example: A random string was ydoat. Querying this with the above url results in only one video with the id VEBt0Hxp5Q8, which does not fit. The video probably contains the string in its description somewhere. If I search for ydoat via https://www.youtube.com/results?q=ydoat, no result is found. Searching for v%3Dydoat (v=ydoat) leads to the same results.

需要进行最后一次检查。示例:随机字符串是ydoat。使用上面的url查询此结果只会导致一个ID为VEBt0Hxp5Q8但不适合的视频。视频可能在某处包含其描述中的字符串。如果我通过https://www.youtube.com/results?q=ydoat搜索ydoat,则找不到任何结果。搜索v%3Dydoat(v = ydoat)会得到相同的结果。

See it in action @ http://cor-forum.de/randomtube/

在行动中查看它@ http://cor-forum.de/randomtube/

edit. source in php: https://github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

编辑。 php中的源代码:https://github.com/phil294/-Php-Randomtube-random-YouTube-video-generator-

Like Anton, I found 4 random characters will be best fitting.

像安东一样,我发现4个随机字符最合适。

#7


1  

I know it's a little bit off-topic but I can offer the following bash script. I use it on my Raspberry Pi and it works quite well.

我知道它有点偏离主题,但我可以提供以下bash脚本。我在我的Raspberry Pi上使用它并且效果很好。

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-5};echo)
    echo "$rand"
    searchresult=$(googler -C -n 100 --np -x -w https://www.youtube.com "$rand")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Prerequisites are that you have installed googler and youtube-dl. My initial idea was to generate random 11 character strings and to append them to the base URL for YouTube videos. However, the number of possible permutations is enormous (26 capital letters + 26 small letters + 10 digits + hyphen + underscore = 64 characters; 64^11=7.38x10^19 permutations) and will be used up if every person on the Earth uploads 10 billion videos. That's why randomly generating the complete 11-character identifier is not a practicable approach. My script generates random 5-character strings instead (variable "rand") and passes them as a search query to googler. Googler searches the YouTube site for these random strings and in most cases it returns results (variable "searchresult"). In case there is no result, the search is repeated with another random string and so on till success. Usually it takes one to three tries. I tried with different lengths of the search string - 4 is maybe not unique enough and 6 is too long and it can take a lot of tries to get a result and I observed that if the script sends more than 10 search requests in short time, Google temporarily blocks me from further searches.

先决条件是你已经安装了googler和youtube-dl。我最初的想法是生成随机的11个字符串,并将它们附加到YouTube视频的基本URL。然而,可能的排列数量是巨大的(26个大写字母+ 26个小写字母+10个数字+连字符+下划线= 64个字符; 64 ^ 11 = 7.38x10 ^ 19个排列)并且如果地球上的每个人上传都会用完100亿个视频。这就是为什么随机生成完整的11个字符的标识符不是一个切实可行的方法。我的脚本生成随机的5个字符的字符串(变量“rand”)并将它们作为搜索查询传递给googler。谷歌搜索YouTube网站上的这些随机字符串,在大多数情况下,它会返回结果(变量“searchresult”)。如果没有结果,则用另一个随机字符串重复搜索,依此类推,直到成功为止。通常需要一到三次尝试。我尝试使用不同长度的搜索字符串--4可能不够独特且6太长并且可能需要大量尝试才能得到结果我观察到如果脚本在短时间内发送超过10个搜索请求,谷歌暂时阻止我进一步搜索。

In the next step, the script extracts the hyperlinks to the YouTube videos from the search results and puts them in the variable "urls". Then one of them is randomly selected to be played (variable "url") and passed to the player - omxplayer in my case, but you can replace it with whichever player you want. Omxplayer is nice on the Raspberry Pi because it uses the hardware acceleration and outputs via hdmi directly to my TV set. If I change "-o hdmi" to "-o local" the audio is sent via the 3.5 mm stereo jack to an external amplifier. Pressing "q" during play stops playing the current video and the next random one starts automatically. It will go on forever till you press Ctrl-C to stop the script.

在下一步中,脚本会从搜索结果中提取指向YouTube视频的超链接,并将它们放入变量“urls”中。然后随机选择其中一个进行播放(变量“url”)并传递给播放器 - 在我的情况下为omxplayer,但你可以用你想要的任何一个播放器替换它。 Omxplayer在Raspberry Pi上很不错,因为它使用硬件加速并通过hdmi直接输出到我的电视机。如果我将“-o hdmi”更改为“-o local”,音频将通过3.5 mm立体声插孔发送到外部放大器。在播放期间按“q”将停止播放当前视频,下一个随机视频将自动开始播放。它会一直持续到你按Ctrl-C来停止脚本。

Additional tips

With some modifications you can get random videos on a given topic. For example, if we put "Deep Purple" as an additional search term we'll get random music videos by Deep Purple:

通过一些修改,您可以获得给定主题的随机视频。例如,如果我们将“Deep Purple”作为附加搜索词,我们将获得Deep Purple的随机音乐视频:

    #!/bin/sh
    while [ true ];
    do
    searchresult=""
    while [ -z "$searchresult" ]; do
    rand=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-2};echo)
    echo "$rand"
    searchresult=$(googler -C -n 10 --np -x -w https://www.youtube.com "$rand" "Deep Purple")
    done
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

Note that in the last example I have reduced the randomness factor to a 2-character string because it will be difficult to find a match for a 5-character string in the relatively small subset of all YouTube videos that contain the search term "Deep Purple". Also here I have limited the number of returned search results by googler to 10 to keep them relevant. With 100 I would also get less relevant results like videos of amateurs trying to play songs by Deep Purple.

请注意,在最后一个示例中,我将随机因子减少为2个字符的字符串,因为在包含搜索词“Deep Purple”的所有YouTube视频的相对较小的子集中,很难找到5个字符的字符串匹配项”。此外,我还将googler返回的搜索结果数量限制为10以保持相关性。有100个我也会得到不太相关的结果,如业余爱好者试图播放Deep Purple的歌曲。

The next script will play randomly only new videos that have been uploaded within the last 12 hours:

下一个脚本将仅随机播放过去12小时内上传的新视频:

    #!/bin/sh
    while [ true ];
    do
    searchresult=$(googler -C -n 100 --np -t h12 -x -w https://www.youtube.com "")
    urls=$(echo "$searchresult" | grep -o "https://www.youtube.com/watch?v=...........")
    url=$(shuf -e -n 1 $urls)
    echo "$url"
    omxplayer -o hdmi $(youtube-dl -f mp4 -g "$url")
    done

You can set different time constraints. See the documentation of googler for more details.

您可以设置不同的时间限制。有关更多详细信息,请参阅googler的文档。

#8


0  

Get a list of words, with hundreds or thousands of words. Then randomly select 2 words from it and use it as a query. This can also be useful if you want to have certain control of how random it could be. For instance you can have a list of english words, or a list of german words. Or have a smaller curated list with words only relevant to a topic you're interested in.

获取包含数百或数千个单词的单词列表。然后从中随机选择2个单词并将其用作查询。如果您想要对其随机性进行一定的控制,这也很有用。例如,您可以拥有英语单词列表或德语单词列表。或者有一个较小的策划列表,其中的单词仅与您感兴趣的主题相关。

#9


-1  

I coded a Python script using YouTube Data API v3. Generally, it is finding random videos according to a small keyword trick. For example, when you take a video, your phone will save it like "IMG 20180815", so search for these default filenames (IMG XXXX-XX-XX), take the ID of one of the randomly selected search result, then you have a random and unseen video.

我使用YouTube Data API v3编写了一个Python脚本。一般来说,它是根据一个小的关键字技巧找到随机视频。例如,当您拍摄视频时,您的手机会将其保存为“IMG 20180815”,因此搜索这些默认文件名(IMG XXXX-XX-XX),获取随机选择的搜索结果之一的ID,然后您拥有随机和看不见的视频。

https://github.com/n1rv4n4/random-youtube-video-generator

Example project website: https://www.randomyoutubevideo.com

示例项目网站:https://www.randomyoutubevideo.com