Using Python & BeautifulSoup to play the lottery

                        Import modules we will need.

In [1]:
from bs4 import BeautifulSoup
import requests
import pandas as pd

Get the lotto results for a specific month/year and day.
day=0 means all in this case, so depenending on the month there will be 4 or 5 draws.
The olg site handles all of this through POST.

In [2]:
def fetch(selectedMonthYear='042013', day='0'):
    url = ""
    payload = {'gameID' : '73',
               'command' : 'submit',
               'selectedMonthYear' : selectedMonthYear,
               'day' : day,
               'language' : 'en'}
    data =, data=payload)
    soup = BeautifulSoup(data.text)
    table = soup.find('table', attrs={'id':'lottery_border'})
    numbers = []
    for row in table.findAll('tr'):
        col = row.findAll('td')
        if len(col) == 5:
            first_set = col[1].find('p',
        # Most draws will only have one set of numbers, but some have bonus draws.  
        # The bonus draws are generated by computer, not the balls so we only
        # take the first set
            for num in first_set[0].split():

Parse out the available list of Month/Year draws and use them to case fetch,
building a list of numbers.

In [3]:
def fetchAll():
    url = ""
    winningNumbers = []
    data = requests.get(url)
    soup = BeautifulSoup(data.text)
    monthYear = soup.find('select', attrs={'name':'selectedMonthYear'})
    NumMonthYear = [option.get('value') for option in monthYear.findAll('option')]
    for date in NumMonthYear:
        for num in fetch(selectedMonthYear=date):
    return winningNumbers

Use fetchAll() to build a list of all the winning numbers. Then build a dict counting the occurance of each number

In [4]:
raw_data = fetchAll()
data = {}
for num in raw_data:
    if num in data:
        data[num] += 1
        data[num] = 1

Construct the dataframe and produce a chart, sorting the most successful numbers to the top

In [5]:
df = pd.DataFrame.from_dict(data, orient='index')
df = df.sort(columns=[0])
chart = df.plot(kind='barh', figsize=(12,12))
chart.set_ylabel('Lotto Numbers')
chart.set_xlabel('Number of Occurances')
<matplotlib.text.Text at 0x7f72d5272b00>