0

Is there any way to generate a valid youtube URL with python

import requests 
from string import ascii_uppercases, ascii_lowercase, digits
charset = list(ascii_uppercase) + list(ascii_lowercase)+ list(digits)

def gen_id():

    res = ""
    
    for i in range(11):
        res += random.choice(charset)
    return res

youtube_url = "https://www.youtube.com/watch?v=" + gen_id()
resp = requests.get(youtube_url)
print (resp.status_code)

I am using this example to generate random youtube url I get response code 200 but no video found when i try to open the video in the browser

I looked at this method but it does not work

max.syntax
  • 63
  • 1
  • 7
  • 2
    Not every possible ID will have a video associated with it. If it did, no one would be able to upload any new videos because there wouldn't be free IDs to associate with them. You're looking for needles in haystacks, try more ids. – Jared Smith Aug 23 '21 at 20:37
  • Does this answer your question? [How to check if a youtube video exists using python?](https://stackoverflow.com/questions/68818442/how-to-check-if-a-youtube-video-exists-using-python) – Matiiss Aug 23 '21 at 20:38
  • Piggybacking on what @JaredSmith said, I believe the best approach is to have some kind of loop that continuously checks if the video exists... although YouTube might rate limit you pretty hard. – dir Aug 23 '21 at 20:40

2 Answers2

0

ID's are generated randomly, and are not that predictable. They are all supposedly Base64 though, which helps limit the number of characters (you will probably want to add dashes and underscores to your random generation since codes like gbhDL8BT_w0 are possible). The only real approach known is generation and then testing, and as some commenters mentioned, this might get rate-limited by YouTube.

There are some additional details provided in this answer to a similar question that might help in doing the generation, or satiating curiosity.

Kieran Wood
  • 1,297
  • 8
  • 15
0

It's not possible to pick always a valid random url from all the videos Youtube has, not every valid sequence is a valid id. You have to check yourself that the urls you want to choose randomly are valid. Pick some videos up and put them in a list.

myUrls = [
           "https://www.youtube.com/watch?v=...",
           "https://www.youtube.com/watch?v=...",
           ...
         ]
youtube_url = random.choice(myUrls)