LOTTO MAX is new replacement to the old Super 7 lottery
When the MAXMILLIONS hit, you might have to check 20+ lottery numbers against your numbers.
This is annoying, and can take a bit to check your tickets.
Well… I got sick and tired of checking my LOTTO MAX tickets.
I figure that the time spent on this will easily save me time in the long run.
Beautiful Soup 3.2.0 is a Python HTML/XML parser designed for quick turnaround projects like screen-scraping.
python lottomax.py [date] [numbers] date - yyyymmdd numbers - 1,2,3,4,5,6,7 EXAMPLE: python lottomax.py 20101231 1,2,3,4,5,6,7
-={ Click here to show the code. }=-
-={ Click here to hide the code. }=-
import sys import urllib2 from datetime import datetime from BeautifulSoup import BeautifulSoup import re, string from decimal import Decimal URL = "http://www.wclc.com/app/winning_numbers/print_win_num.html?pageName=lotto_max_extra.html&monthYear=%s" LOTTOMAX = "http://www.wclc.com/app/winning_numbers/prize_breakdown.html?pageName=lotto_max_extra.html&gameId=%s" # Fake out the server.. let's be Firefox today! HEADER = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13' NOMAXMILLIONS = "No MAXMILLIONS draws this week" PATTERN = re.compile('[\W_]+') PATTERNALPHA = re.compile('[a-zA-Z]+') PATTERNNUMBER = re.compile('[a-zA-Z $:,]+') PATTERNALPHANUMCLEAN = re.compile('[^a-zA-Z1-9 ]+') # print developer debugging information. DEBUG = False # Use mainpage.html and output.html instead of bashing the servers for testing purposes # Don't want to get banned.. from to many requests USEHTML = False # Set to save a new copy of the html files for testing GETNEWHTML = False USAGE = """I was too lazy to continously check the lotto max numbers manually... so I wrote this Lotto Max Checker. USAGE: %s [date] [numbers] date - yyyymmdd numbers - 1,2,3,4,5,6,7 EXAMPLE: %s 20101231 1,2,3,4,5,6,7"""; def usage(): print USAGE.replace("%s",sys.argv[0]); def moneyfmt(value, places=2, curr='', sep=',', dp='.', pos='', neg='-', trailneg=''): """ http://docs.python.org/library/decimal.html Convert Decimal to a money formatted string. places: required number of places after the decimal point curr: optional currency symbol before the sign (may be blank) sep: optional grouping separator (comma, period, space, or blank) dp: decimal point indicator (comma or period) only specify as blank when places is zero pos: optional sign for positive numbers: '+', space or blank neg: optional sign for negative numbers: '-', '(', space or blank trailneg:optional trailing minus indicator: '-', ')', space or blank >>> d = Decimal('-1234567.8901') >>> moneyfmt(d, curr='$') '-$1,234,567.89' >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-') '1.234.568-' >>> moneyfmt(d, curr='$', neg='(', trailneg=')') '($1,234,567.89)' >>> moneyfmt(Decimal(123456789), sep=' ') '123 456 789.00' >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>') '<0.02>' """ q = Decimal(10) ** -places # 2 places --> '0.01' sign, digits, exp = value.quantize(q).as_tuple() result = [] digits = map(str, digits) build, next = result.append, digits.pop if sign: build(trailneg) for i in range(places): build(next() if digits else '0') build(dp) if not digits: build('0') i = 0 while digits: build(next()) i += 1 if i == 3 and digits: i = 0 build(sep) build(curr) build(neg if sign else pos) return ''.join(reversed(result)) def main(argv=None): if argv == None: argv = sys.argv if len(argv) <> 3: print "Invalid arguments passed." usage(); sys.exit(-1); try: date = str(argv[1]) except: date = None if date == None: print "Invalid date passed." usage(); sys.exit(-1); try: date_object = datetime.strptime(date, '%Y%m%d') except: date_object = None if date_object == None: print "Invalid date passed." usage(); sys.exit(-1); try: mynumbers = str(argv[2]).split(",") except: mynumbers = None try: for numb in mynumbers: int( numb ) except: mynumbers = None if mynumbers == None or len(mynumbers) <> 7: print "Invalid numbers passed." usage(); sys.exit(-1); checkDate = date_object.strftime("%a. %b %d, %Y") print "" print "Checking %s for numbers %s" % ( checkDate, argv[2] ) print "" #if 1==1: # sys.exit(-1) GameId = None request = urllib2.Request( URL % date_object.strftime("%m%Y") ) request.add_header('User-Agent', HEADER) #opener = urllib2.build_opener( urllib2.HTTPHandler(debuglevel=2) ) opener = urllib2.build_opener( urllib2.HTTPHandler()) html = None if GETNEWHTML: html = opener.open(request).read() FILE = open("mainpage.html","w") FILE.write( html ) FILE.close() elif USEHTML: FILE = open("mainpage.html","r") html = FILE.read() FILE.close() else: html = opener.open(request).read() soup = BeautifulSoup(html) for found in soup.findAll('a', attrs={"style" : "font-size:13px"}): if found.getText() == checkDate: if DEBUG: print "Found lottery date." GameId = found['onclick'].split("'")[3] if GameId == None: print "Could not find a game on %s." % checkDate sys.exit(-1) else: if DEBUG: print "Found game ID: %s" % GameId request = urllib2.Request( LOTTOMAX % GameId ) request.add_header('User-Agent', HEADER) html = None if USEHTML: FILE = open("output.html","r") html = FILE.read() FILE.close() else: html = opener.open(request).read() if GETNEWHTML: FILE = open("output.html","w") FILE.write( html ) FILE.close() soup = BeautifulSoup(html) # Pop open tblHeader2 table.. # grab numbers, bonus, and jackpot found = soup.find('table', attrs={"id":"tblHeader2","class":"tableGrid"} ) found = found.findAll('td') numbers = PATTERN.sub('', found[0].getText() ).split("nbsp") bonus = int( PATTERNALPHA.sub('', PATTERN.sub('', found[1].getText() ) ) ) jackpot = Decimal( PATTERNNUMBER.sub('', found[2].getText() ) ) numbers.remove("") numbString = ','.join(numbers) print "Lottery Information" print "-=-=-=-=-=-=-=-=-=-" print "Lottery Draw Numbers: %s" % numbString print "Bonus Number: %s" % bonus print "Total Jackpot: $%s" % moneyfmt( jackpot ) # Pop open grid table.. # grab prize information prizeDict = {} prizeInfoDict = {} found = soup.find('table', attrs={"id":"grid"} ) for tr in found.findAll('tr'): th = tr.findAll('th') if len( th ) <> 0: continue td = tr.findAll('td') winType = td[0].getText() numbWinners = td[1].getText() prize = td[2].getText() #print prize prizeInfoDict = {} prizeInfoDict["numbWinners"] = numbWinners if prize == "FREE PLAY": prizeInfoDict["prize"] = str( prize ) elif prize == "CARRIED OVER": prizeInfoDict["prize"] = str( prize ) else: prizeInfoDict["prize"] = PATTERNNUMBER.sub('', str( prize ) ) prizeDict[ str(winType) ] = prizeInfoDict #for k,v in prizeDict.iteritems(): # print k,v # Pop open tblContent table.. # grab extra information found = soup.find('table', attrs={"id":"tblContent"} ) found = found.find('font', attrs={"style":"FONT-FAMILY: ARIAL; FONT-SIZE: 12pt;" } ) extra = PATTERN.sub('', found.getText() ) print "Extra: %s" % extra # Pop open bottom tables.. # grab max millions information found = soup.findAll('table', attrs={"style":"border-bottom: #000000 1px solid"}) foundMaxMillions = found[2] found = foundMaxMillions.find("span",attrs={"style":"FONT-FAMILY: ARIAL; FONT-SIZE: 12pt;" } ) status = PATTERNALPHANUMCLEAN.sub('', found.getText() ) maxMillionsFound = False if status == NOMAXMILLIONS: print "No Max Millions for this draw." else: maxMillionsFound = True maxMillionsDataSet = [] maxMillionNumber = [] maxMillionSet = {} if maxMillionsFound: #print "Maxmillions were found." found = soup.findAll('table', attrs={"id":"grid"} ) foundtr = found[1].findAll('tr') for tr in foundtr: maxMillionNumber = [] tdsFound = tr.findAll("td") if len( tdsFound ) == 0: # Damn header line continue foundMaxmillions = tdsFound[0].findAll("span", attrs={'class' : re.compile("maxmillionsPrizeBreakdown*")} ) #print foundMaxmillions for maxmillion in foundMaxmillions: maxMillionNumber.append( int( maxmillion.getText() ) ) maxMillionSet = {} maxMillionSet["number"] = maxMillionNumber maxMillionSet["numbWinners"] = Decimal( PATTERNNUMBER.sub('', tdsFound[1].getText() ) ) maxMillionSet["prizeWon"] = Decimal( PATTERNNUMBER.sub('', tdsFound[2].getText() ) ) maxMillionsDataSet.append( maxMillionSet ) print "There are %s maxmillion draws to check" % len( maxMillionsDataSet ) # Let's check the numbers!!! # 1st check the main draw numbers found = 0 bonusFound = False for mynumber in mynumbers: if mynumber in numbers: found = found + 1 if int( mynumber ) == int( bonus ): bonusFound = True print "" print "Results" print "-=-=-=-" print "You're numbers matched %s out of 7 and you" % found, if bonusFound: print "did", else: print "did not", print "have the bonus number" bonusStr = " + Bonus" if bonusFound else "" winning= "%s of 7" % (found) winningBonus = "%s of 7%s" % (found, bonusStr) if winningBonus in prizeDict: if prizeDict[str(winningBonus)]["prize"] == "FREE PLAY": print "You won a free play." elif prizeDict[str(winningBonus)]["prize"] == "CARRIED OVER": print "Carried Over." else: print "You won: $%s" % moneyfmt( Decimal( prizeDict[winningBonus]["prize"] ) ) print "Number of winners: %s" % prizeDict[winningBonus]["numbWinners"] elif winning in prizeDict: if prizeDict[str(winning)]["prize"] == "FREE PLAY": print "You won a free play." elif prizeDict[str(winningBonus)]["prize"] == "CARRIED OVER": print "Carried Over." else: print "You won: $%s" % moneyfmt( Decimal( prizeDict[winning]["prize"] ) ) print "Number of winners: %s" % prizeDict[winning]["numbWinners"] else: print "Sorry, you did not win anything on the draw." if maxMillionsFound: print "" print "Max Millions" print "-=-=-=-=-=-=" maxMillion = None WinnerFound = False for maxMillion in maxMillionsDataSet: #print maxMillion Winner = True for numb in maxMillion["number"]: if "%s" % numb not in mynumbers: Winner = False break if Winner: break if Winner: print "You won $%s in the maxmillion draw!" % moneyfmt( Decimal( maxMillion["prizeWon"] )) print "Number of winners: %s" % maxMillion["numbWinners"] else: print "Sorry you did not win any of the maxmillion draws." if __name__ == "__main__": main()