Home > Fantacalcio, python > Fantagazzetta parser

Fantagazzetta parser

3 Dicembre 2014

un piccolo script per scrivere su un foglio di calcolo, i voti di Fantagazzetta.com.
Il file scaricato dal sito è un html mascherato, pertanto il parsing viene fatto con BeautyfulSoap e riscritto con xlwt:

import xlwt
import wx
import os
from BeautifulSoup import BeautifulSoup as bsoup


class FileBrowser(wx.FileDialog):
    '''Class for file browser'''
    def __init__(self):
        super(FileBrowser, self).__init__(None, "XLS file", os.getcwd(),
                "", "Excel file (*.xls)|*.xls|" "All files (*.*)|*.*",
                wx.OPEN)
        if self.ShowModal() == wx.ID_OK:  
            self.file = self.GetPath()
        else:
            self.file = ''
        self.Destroy()
        

def parse_html(path):
    voti = []

    with open(path) as html_file:
        data = html_file.read()

    soup = bsoup(''.join(data))
    for row in soup.findAll('tr'):
        cells = row.findAll('td')
        try:
            name= cells[2].text
            v = float('%.1f' % float(cells[3].text.replace(',', '.')))
            gf = int(cells[4].text)
            gs = int(cells[5].text)
            rp = int(cells[6].text)
            rno = int(cells[7].text)
            rok = int(cells[8].text)
            ag = int(cells[9].text)
            am = int(cells[10].text)
            es = int(cells[11].text)
            ass = int(cells[12].text)
            asf = int(cells[13].text)

        except (IndexError, ValueError):
            pass

        else:
            if v == '6*':
                fv = '0.0'
            else:
                fv = v + 3*gf - gs + 3*rp - 3*rno + 3*rok - 3*ag \
                     - 0.5*am - es + ass + asf
            voti.append((name, fv))
    return voti


def write_to_excel(iterable):
    wb = xlwt.Workbook()
    ws = wb.add_sheet('Voti')
    for n in range(len(iterable)):
        ws.write(n, 1, iterable[n][0])
        ws.write(n, 3, iterable[n][1])
    wb.save('VotiUltimaGiornataHtml.xls')


def main():
    '''app starter'''
    app = wx.PySimpleApp()
    path = FileBrowser().file
    if path:
        voti = parse_html(path)
        print 'processing...'
        write_to_excel(voti)
        print '...Done!'
    else:
        print 'Aborted!'
    app.MainLoop()

if __name__ == '__main__':
    main()
Categorie:Fantacalcio, python Tag:
I commenti sono chiusi.