How to download youtube video using python script

I need to download a video from youtube using a python script. However, I cannot get the video url from the YouTube page.

For example, given the URL: http://www.youtube.com/watch?v=5qcmCUsw4EQ&feature=g-all-u&context=G2633db8FAAAAAAAAAAA

  • I need to download video as flv or any other format. Also I need to be able to upload multiple qualities of it.
  • I tried several scripts like youtube-dl and quvi but they all give errors and don't work. Please help. He must be deeply appreciated.
+1


source to share


1 answer


You need to parse the flashvars

tag variable <embed>

that contains the video. They change around, so it might take some experimentation to find the current variable names. Roughly speaking, you will want to use type libraries mechanize

to grab the HTML page and BeautifulSoup

to parse the HTML and extract the flashvars

element field <embed>

. Then look at the variables to figure out which one contains the video url.

eg,



  br = mechanize.Browser()
  # Browser options
  br.set_handle_equiv(True)
  br.set_handle_redirect(True)
  br.set_handle_referer(True)
  br.set_handle_robots(False)
  # Follows refresh 0 but not hangs on refresh > 0
  br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
  # User-Agent (this is cheating, ok?)
  br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
  br.open('%s?v=%s' % (YOUTUBE_URL, vidId))
  soup = BeautifulSoup.BeautifulSoup(br.response().read())
  flashVars = urllib2.urlparse.parse_qs(soup.find('embed').get('flashvars'))
  # Return the first second video source URL
  return flashVars['fmt_stream_map'][0].split('|')[1]

      

+10


source







All Articles