Created
August 9, 2012 10:11
-
-
Save emillon/3302945 to your computer and use it in GitHub Desktop.
Random Walk on Youtube
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import random | |
import sys | |
import urllib2 | |
from bs4 import BeautifulSoup | |
def video_open(vid): | |
url = 'http://www.youtube.com' + vid | |
return urllib2.urlopen(url) | |
def select_video(vids): | |
lamb = 0.5 | |
i = min(int(random.expovariate(lamb)), len(vids) - 1) | |
return vids[i] | |
def related_videos(vid): | |
soup = BeautifulSoup(video_open(vid)) | |
wr = soup.find(id='watch-related') | |
r = [] | |
for c in wr.children: | |
if 'video-list-item' not in c['class']: | |
continue | |
link = c.find('a') | |
href = link['href'] | |
if 'relchannel' in href: | |
continue | |
title = link.find(attrs={'class': 'title'})['title'] | |
r.append ((href, title)) | |
return r | |
def main(): | |
vid = '/watch?v=mbUVtfUWwF8' # Chuck testa song | |
if len(sys.argv) > 1: | |
vid = '/watch?v=' + sys.argv[1] | |
for i in range(0, 30): | |
vids = related_videos(vid) | |
newvid = select_video(vids) | |
print "http://youtube.com%-50s %s" % newvid | |
vid = newvid[0] | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment