Tenderlove Making

Automated Youtube Uploads

I thought I would share the part of my twitterbrite scripts that uploads videos to Youtube. Its about 30 lines long, and took me an hour or so to write. Most of my time was spent figuring out form fields to fill out rather than writing code though….

I’ve broken the script down to three parts: logging in, setting the video attributes, and uploading the video file.

Step 1: Logging In

The first step is pretty simple. Just instantiate a new mechanize object, fetch youtube.com, set your login credentials, and submit! ~~~ ruby agent = WWW::Mechanize.new { |a| a.user_agent_alias = ‘Mac Safari’ } page = agent.get(‘http://youtube.com/’)

Login

page.form(‘loginForm’) { |f| f.username = ‘username’ f.password = ‘password’ }.submit ~~~

Step 2: Setting video attributes

This is probably the most difficult step. Now that the agent is logged in, we have to fetch the upload page and fill out the video attributes form. You have to set the title, description, category, and keywords for your video. The you have to tell the agent to click a special button. ~~~ ruby # Set the video attributes page = agent.get(‘http://youtube.com/my_videos_upload’) form = page.form(‘theForm’) form.field_myvideo_title = ‘My video title’ form.field_myvideo_descr = “My video description” form.field_myvideo_categories = 28 form.field_myvideo_keywords = ‘my tag’ page = form.submit(form.buttons.name(‘action_upload’).first) ~~~ The number “28” is just the value from the category drop down list. You can iterate over the select options using mechanize, but I leave that as an exercise to the reader.

Step 3: Upload the video file

My script expects that the video file name will be supplied on the command line, so ARGV[0] should point to the file you want to upload. In this step, you simply set the video file name, then submit the form. ~~~ ruby # Upload the video page = page.form(‘theForm’) { |f| f.file_uploads.name(‘field_uploadfile’).first.file_name = ARGV[0] }.submit page.body =~ /<textarea[^>]>(.)<\/textarea>/m puts $1 ~~~ The last two lines grab the html needed to display the video and prints it.

There you go. Upload lots of videos now! Yay!

« go back