#Now that we know the format of the web pages #returned by Yahoo! finance, #we can write an application that extracts the #stock price information and displays it in #a useful way. This function takes the stock #ticker code as a parameter, returns 0 if #a nonexistent ticker code is passed, -1 if #the information is not in the expected format #(for example, if the layout of the website #has changed), and otherwise a list of two #strings, giving the time and the stock price. from urllib import * def getStockPrice2(stock_code): webstream=urlopen("http://finance.yahoo.com/q?s="+stock_code) results=webstream.readlines() webstream.close() #if there's an invalid stock identifier, #then line 92 of the page contains error information if len(results)>92 and results[92].find("There are no") != -1: result = 0 #otherwise, line 9 contains the price and time of day, #which we now proceed to extract from the string else: priceline=results[9] loc1=priceline.find("yfs_t10") loc2=priceline.find(">",loc1) loc3=priceline.find("<",loc2) loc4=priceline.find("yfs_l10") loc5=priceline.find(">",loc4) loc6=priceline.find("<",loc5) if -1 in [loc1,loc2,loc3,loc4,loc5,loc6]: #if this happens, then the website's format must #have changed result=-1 else: time=priceline[loc2+1:loc3] price=priceline[loc5+1:loc6] result=[time,price] return result def testGetStockPrice2(stockCode): v=getStockPrice2(stockCode) if v==0: print "Invalid stock code." elif v==-1: print "The format of the web page source may have changed!" else: print "Price at time "+v[0]+": "+v[1]