/
data.py
66 lines (47 loc) · 1.75 KB
/
data.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
from bs4 import BeautifulSoup
import pandas as pd
import requests
THIS_YEAR = "2020"
BASE_URL = "https://www.pro-football-reference.com"
class Data:
def __init__(self):
self.player_dict = self.players()
def fant_raw(self, year=THIS_YEAR):
F = f'https://www.pro-football-reference.com/years/{year}/fantasy.htm'
r = requests.get(F)
soup = BeautifulSoup(r.text, 'lxml')
return soup
def players(self, year=THIS_YEAR):
soup = self.fant_raw(year=year)
# table = soup.find(id="fantasy")
players = soup.find_all("td", {"data-stat": "player"})
player_dict = {}
for player in players:
name = player.text.strip()
link = player.find('a')['href']
player_dict[name] = link
return player_dict
def fantasy_df(self, year=THIS_YEAR):
soup = self.fant_raw(year=year)
table = soup.find(id="fantasy")
df = pd.read_html(str(table), header=1)[0]
df['Player'] = df['Player'].apply(lambda x: x.strip())
return df
def career_stats(self, player_name, advanced=False):
if player_name in self.player_dict:
if advanced is True:
prof_link = (BASE_URL + self.player_dict[player_name][:-4] +
'/gamelog/advanced')
else:
prof_link = (BASE_URL + self.player_dict[player_name][:-4] +
'/gamelog/')
else:
print('No player record!')
df = pd.read_html(prof_link, header=1)[0]
df = df[df['Age'] != 'Age']
df.drop(df.tail(1).index, inplace=True)
return df
# Data = Data()
# print(Data.fantasy_df())
# print(Data.players())
# Data.career_stats('Tom Brady')