O'Reilly Hacks
oreilly.comO'Reilly NetworkSafari BookshelfConferences Sign In/My Account | View Cart   
Book List Learning Lab PDFs O'Reilly Gear Newsletters Press Room Jobs  


 
Buy the book!
Yahoo! Hacks
By Paul Bausch
October 2005
More Info

HACK
#45
Create a TV Watch List
Combine Yahoo! TV with Yahoo! Calendar to build a custom TV schedule
The Code
[Discuss (0) | Link to this hack]

The Code

This hack relies on the web automation module WWW::Mechanize (called Mech) and the WWW::Yahoo::Login module. This code logs in to Yahoo! TV with your Yahoo! ID and password, searches for the provided keyword, and adds all of the results to your Yahoo! Calendar. To get started, add the following code to a file called tv_watchlist.pl and include your Yahoo! ID and password in the code:

	#!/usr/bin/perl
	# tv_watchlist.pl
	# A script to gather programs from a Yahoo! TV search
	# and add them to a Yahoo! Calendar
	# Usage: tv_watchlist.pl <query>

	use strict;
	use WWW::Yahoo::Login qw( login logout );
	use WWW::Mechanize;

	# Set your account info
	my $user = "insert Yahoo! ID";
	my $pass = "insert Yahoo! Password";
	my $count = 0;

	# Grab the incoming query
	my $query = join(' ', @ARGV) or die "Usage: tv_watchlist.pl <query>\n";

	# Set login URL
	my $url = 'http://e.my.yahoo.com/config/login?';
	   $url .= '.intl=us&.src=tv&.done=http%3a//tv.yahoo.com/';
	   $url .= 'grid%3f.force=p%26setlineupcookie=true';

	# Log into Yahoo! TV
	my $mech = WWW::Mechanize->new();
	my $login = login(
		mech => $mech,
		uri  => $url,

		user => $user,
		pass => $pass,
	);

	# If login succeeded, add each program to calendar
	if ($login) {
		my $form = $mech->form_number(3);
		$mech->field("title", "\"$query\"");
		$mech->click();
		my $response = $mech->response()->content;
		while ($response =~ m!<a href="(http://tv.*?tvpdb.*?)">.*?</a>!gis) {
			my $showlink = $1;
			$showlink =~ s!\n!!gs;
			$mech->get( $showlink );
			$mech->follow_link( url_regex => qr/calendar/ );
			$mech->follow_link( text_regex => qr/Add to/ );
			my $result = $mech->response()->content;
			if ($result =~ m!<div class="alertbox">(.*?)</div>!gis) {
				$count++;
				my $msg = $1;
				$msg =~ s!<.*?>!!gs;
				$msg =~ s!\n!!gs;
				print "$msg\n";
			}
		}
	} else {
			warn $WWW::Yahoo::Login::ERROR;
	}

	if ($count == 0) {
		print "No shows added.";
	}

Because adding shows from Yahoo! TV search results to a Yahoo! Calendar can be accomplished by clicking a predictable series of links, the Mech function follow_link does most of the work in this script. A simple regular expression for either the URL or text of a link on the page tells Mech which links to follow.


O'Reilly Home | Privacy Policy

© 2007 O'Reilly Media, Inc.
Website: | Customer Service: | Book issues:

All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.