View posts for Tag: "shell script"

How to download videos from YouTube

YouTube is the world’s #1 source for more or less funny or interesting videos. Unfortunately YouTube does not offer any options to download the videos from their site. YouTube even hides the direct links to their video resources. Even though it’s quite easy to find a download link for the real .flv videos:

  • Just go to the site where your desired video is i.e. http://de.youtube.com/watch?v=-xEzGIuY7kw .
  • View the source code of the site and search for a section that starts with “swfArgs”.
  • From this section you need the values for “video_id” and “t” (i.e. “video_id”: “dsfaAfdaAfs” and “t”: “sdfkljasldfjlkasflshdfjaiosjjsknfjkhJhjdf”)
  • With these values you should be able to call “http://www.youtube.com/get_video.php?video_id=<your video_id value>&t=<your t vlaue>” and to download your desired video.

I’ve made a little shell script for Linux and Mac that does all the searching stuff for me and that returns the url to the video source.

#!/bin/sh

if [ $1 == "" ]; then echo -e "$0: No URL specified\nUsage: $0 <url>\n"; exit 1; fi

which curl > /dev/null
if [ "$?" == 0 ]; then GET_COMMAND=curl
else
  which wget > /dev/null
  if [ "$?" == 0 ]; then echo "Didn't find curl nor wget. Exiting."; exit 1;
  else
    GET_COMMAND=wget -O ytf| cat ytf; rm ytf;
  fi
fi

# Use GNU version of sed on Darwin/OS X
if [ `uname -s` == "Darwin" ]; then SED=gsed;
else SED=sed; fi

RELEVANT_DATA=`$GET_COMMAND $1 | grep 'swfArgs' | $SED 's/,/\n/g'`
VIDEO_ID=`echo "$RELEVANT_DATA" | grep 'video_id' | $SED 's/"//g' | $SED 's/ //g' | $SED 's/:/=/g'`
T=`echo "$RELEVANT_DATA" | grep 't"' | $SED 's/"//g' | $SED 's/ //g' | $SED 's/:/=/g'`

LINK="http://www.youtube.com/get_video.php?$VIDEO_ID&$T"

if [ "$VIDEO_ID" != "" ] && [ "$T" != "" ]; then echo $LINK; exit 0;
else echo "Couldn't retrieve the needed data from the specified URL."; exit 1;
fi

To run the script correctly the GNU version of “sed” is needed.

Leave a Comment