-
Notifications
You must be signed in to change notification settings - Fork 1
/
playerCrawler.py
152 lines (124 loc) · 4.74 KB
/
playerCrawler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 10 14:28:49 2014
@author: Gaspard, Thomas, Arnaud
"""
import re, os
from bs4 import BeautifulSoup
from utils import *
from bdd import *
url_players = 'http://www.atpworldtour.com/tennis/players/'
def defaultPlayerCleanFunction(entry):
# entry['RealName'] = getName(entry['IDPlayer']).encode("utf-8")
entry['RealName'] = getName(entry['IDPlayer'])
return entry
def getName(ch):
y = ch[ch.rfind('/')+1:]
auxName = y.replace("-","_")
html = getHTML("http://en.wikipedia.org/w/index.php?title="+auxName+"&action=edit")
y = re.findall("\#.*DIRECT[\s\t]*\[\[[\s\t]*(.*)[\s\t]*\]\]", html)
if len(y) == 0 or y == ['']:
return auxName.replace('_',' ')
else:
return y[0]
class Players:
def __init__(self, fs):
self.dic = dict()
self.ID = 0
self.playersPath = fs.playerPath
self.cleanPlayerPath = fs.cleanPlayerPath
self.i = 0
self.savePeriod = 20
def isTreated(self, code):
for t in self.dic:
if self.dic[t]['Code'] == code:
return True
return False
def addInfoPlayer(self, code):
if self.isTreated(code):
return False
else:
url = urlOpen( url_players + code + '.aspx' )
dom = BeautifulSoup(url)
aux = infoFromDOM(dom)
playerURL = playersFromURL(url)
aux.update( {
"ID" : self.ID,
"Code" : code,
"IDPlayer" : playerURL } )
self.dic[playerURL] = aux
self.ID += 1
self.saveMaybe()
return True
def save(self):
with open(self.playersPath, 'wb') as csvfile:
w = getWriter(csvfile, players_fields)
w.writerows( sorted(self.dic.values(), key=lambda k: k['ID']) )
def load(self):
with open(self.playersPath, 'rb') as csvfile:
self.dic = dict()
self.ID = 0
for p in getReader( csvfile ):
p['ID'] = int( p['ID'] )
if p['ID'] >= self.ID:
self.ID = p['ID'] + 1
self.dic[ p['IDPlayer'] ] = p
def saveMaybe(self):
self.i += 1
if self.i % self.savePeriod == 0:
debug("Saving")
self.save()
def canLoad(self):
return os.path.isfile(self.playersPath)
def clean(self, cleanFunction=defaultPlayerCleanFunction):
chrono = Chrono()
chrono.start( self.ID )
with open( self.cleanPlayerPath , 'wb') as f:
w = getWriter(f, clean_players_fields)
with open( self.playersPath, 'rb' ) as f2:
for e in csv.DictReader(f2, restval='?', delimiter='|'):
w.writerow( cleanFunction(e) )
chrono.tick()
if chrono.needPrint():
debugCL("Player " + str(chrono.i) + chrono.getBar() + " Remains " + chrono.remaining() )
def playersFromURL(url):
return re.findall('Players\/(.*).aspx', url.geturl() )[0]
def infoFromDOM(dom):
country = "NotFound"
try :
country = dom.find('div', {'id':'playerBioInfoFlag'} ).find('p').contents[0]
except:
printError("No country found !")
f = dom.find('ul', {'id':'playerBioInfoList'} ).find_all('li')
birth = ['-1','-1','-1']
height = -1
weight = -1
handed = -1
turnedPro = -1
for li in f:
field = li.find('span').contents[0]
if field == u'Age:':
birth = re.findall('\(([0-9]*)\.([0-9]*)\.([0-9]*)\)', li.getText() )[0]
elif field == u'Birthdate:':
birth = re.findall('([0-9]*)\.([0-9]*)\.([0-9]*)', li.getText() )[0]
elif field == u'Height:':
height = int( re.findall('\(([0-9]*) cm\)', li.getText())[0] )
elif field == u'Weight:':
weight = int( re.findall('\(([0-9]*) kg\)', li.getText())[0] )
elif field == u'Turned Pro:':
turnedPro = int( re.findall(' ([0-9]+)', li.getText())[0] )
elif field == u'Plays:':
if re.findall('Right', li.getText()):
handed = 1
elif re.findall('Left', li.getText()):
handed = 0
return {
'DayBirth' : int( birth[0] ),
'MonthBirth' : int( birth[1] ),
'YearBirth' : int( birth[2] ),
'Height' : height,
'Weight' : weight,
'RightHanded' : handed,
'TurnedPro' : turnedPro,
'Country' : country
}