Step 1: Create API-Key
- Create a google-Account
- Visit: https://console.developers.google.com/
- Create a new project: Click on Create new Project in head-menu and give it a name
- Now Activate the YoutTubeData API: Click it and enable it.
- Insert your Applications-Infos
- Click "create Credentials"
- Klick what do i need?
- Note your API-Key
Now you can access the 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.
Attention: There is a limit of 30,000 units/second/user and 1,000,000 per day.
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:
SELECT 'id'
FROM yttable
WHERE 1 ORDER BY RAND() LIMIT 1
Your random video is:
https://www.youtube.com/embed/[random ID]
Have fun!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…