# web.py - can we read from the Web? # If we go to a stock page on finance.yahoo.com, we can # read a quote, which appears on a line that contains something # like this, in the case of ibm: # yfs_l10_ibm">101.37< # Two situations we don't handle: # URLError in case the URL we have is malformed # Bad stock symbol - the page doesn't have a price in it. import urllib2 import re # Ask user for the stock symbol. For this program to work, it # needs to be in all lowercase letters, so convert. stock = raw_input("Enter stock symbol") stock = stock.lower() page = urllib2.urlopen("http://finance.yahoo.com/q?s=" + stock) for line in page: if line.count("yfs_l10_" + stock) > 0: # We have found the line containing the quote. # First, we chop off everything to the left of the quote. line = line[line.find("yfs_l10_"):] # Now we tokenize on the > and < and grab the 2nd token. toklist = re.compile("[<>]").split(line); price = toklist[1] print "The price of " + stock + " is " + price break