-
Notifications
You must be signed in to change notification settings - Fork 0
/
pvd_Sofascore.py
2198 lines (1734 loc) · 83 KB
/
pvd_Sofascore.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pandas as pd
import re
import requests
import http.client
import json
import time
import os
from bs4 import BeautifulSoup
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# Main functions
def get_teams_from_league(league_url):
"""
Extracts team information from a Sofascore league URL.
Args:
league_url (str): The URL of the league page on Sofascore.
Returns:
list: A list of dictionaries containing team details, including name, ID, logo, league, country, season, and link.
"""
teams_dic = []
seen_links = []
j = 0
# Extract tournament_id and season_id from the URL
parts = league_url.rstrip('/').split('/')
tournament_id = parts[-1].split('#id:')[0]
season_id = parts[-1].split('#id:')[1]
# Use the get_tournament_standing function to get league data
standings = get_tournament_standing(tournament_id, season_id)
if standings is None:
return teams_dic
league = standings['league']
country = standings['country']
season = standings['season']
teams_name = standings['teams_name']
teams_id = standings['teams_id']
try:
response = requests.get(league_url)
soup = BeautifulSoup(response.content, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
href = link['href']
if href not in seen_links:
seen_links.append(href)
if '/es/equipo/futbol/' in href:
full_link = 'https://www.sofascore.com' + href
if j < len(teams_name):
team_info = {
'team': teams_name[j],
'id': teams_id[j],
'logo': f'https://api.sofascore.app/api/v1/team/{teams_id[j]}/image',
'league': league,
'country': country,
'season': season,
'link': full_link
}
teams_dic.append(team_info)
j += 1
except requests.exceptions.RequestException as e:
print(f'Error during request: {e}')
# Export to CSV
os.makedirs('data', exist_ok=True)
teams_df = pd.DataFrame(teams_dic)
teams_df.to_csv('data/sofascore_teams.csv', index=False, encoding='utf-8')
return teams_dic
def get_events_from_league(league_url):
"""
Extracts event results from a Sofascore league URL.
Args:
league_url (str): The URL of the league page on Sofascore.
Returns:
list: A list of dictionaries containing event details, including round number, season, and link.
"""
if not league_url.endswith(',tab:matches'):
league_url += ',tab:matches'
# Set up the driver
driver = webdriver.Chrome() # Or use `webdriver.Firefox()` if you are using Firefox
events_dic = [] # List to store each event result as a separate row
try:
# Go to the URL
driver.get(league_url)
# Wait for the "By Rounds" tab to be clickable and click it
wait = WebDriverWait(driver, 30)
rounds_tab = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'div[data-tabid="2"]')))
rounds_tab.click()
# Wait for the content of the "By Rounds" tab to load
wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '[data-testid="event_cell"]')))
# Get the season text
season_element = driver.find_element(By.CSS_SELECTOR, 'div.Box.Flex.eJCdjm.bnpRyo .Text.nZQAT')
season_text = season_element.text
# Extract the season number from the text
season = season_text.split(' ')[-1] # Get the last element after the space
# Initialize variables
round_number = None
while True:
# Get the round text
round_container = driver.find_element(By.CSS_SELECTOR, 'div.Box.gRmPLj')
round_items = round_container.find_elements(By.CSS_SELECTOR, 'div.Text.nZQAT')
selected_round = None
for item in round_items:
round_text = item.text
if 'Round' or 'Ronda' in round_text:
selected_round = round_text
break
# Extract the round number from the text
current_round_number = selected_round.split(' ')[-1] if selected_round else 'Not found'
if current_round_number == 'Not found':
break
round_number = int(current_round_number)
# Extract event links for the current round
event_cells = driver.find_elements(By.CSS_SELECTOR, '[data-testid="event_cell"]')
for cell in event_cells:
href = cell.get_attribute('href')
if href and 'summary' not in href: # Exclude links containing 'summary'
# Extract tournament information
event_id = re.search(r'#id:(\d+)', href).group(1)
data = get_event_data(event_id)
league = data['event']['tournament']['name']
league_id = data['event']['tournament']['uniqueTournament']['id']
season_id = data['event']['season']['id']
country = data['event']['tournament']['category']['name']
home_team_id = data['event']['homeTeam']['id']
away_team_id = data['event']['awayTeam']['id']
round_result = {
'id': event_id,
'league': league,
'league_id': league_id,
'country': country,
'round': round_number,
'season': season,
'season_id': season_id,
'home_team_id': home_team_id,
'away_team_id': away_team_id,
'link': href
}
events_dic.append(round_result)
# Check if we have reached round 1 and exit the loop if so
if round_number <= 1:
break
# Try to go to the previous round
try:
previous_round_button = driver.find_element(By.CSS_SELECTOR, 'button.Button.iCnTrv')
previous_round_button.click()
# Wait a moment for the page to load
WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, '[data-testid="event_cell"]')))
except Exception as e:
print(f"Error navigating to previous round: {e}")
break
finally:
# Close the browser
driver.quit()
# Export to CSV
os.makedirs('data', exist_ok=True)
events_df = pd.DataFrame(events_dic)
events_df.to_csv('data/sofascore_events.csv', index=False, encoding='utf-8')
return events_dic
def get_players_from_teams(teams, delay=5):
"""
Extracts player information from team URLs on Sofascore.
Args:
teams (list): List of dictionaries, each containing team details and URL.
delay (int): Time to wait (in seconds) between requests to avoid overloading the server. Default is 5 seconds.
Returns:
list: A list of dictionaries with player information.
"""
players_dic = [] # List to store player information
repeated = [] # List to keep track of processed links
for team in teams:
time.sleep(delay) # Respect the delay between requests
team_name = team['team']
season = team['season']
league = team['league']
country = team['country']
url = team['link']
# Make the request and parse the page content
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
href = link['href']
if href not in repeated:
repeated.append(href)
if '/es/jugador/' in href:
full_link = 'https://www.sofascore.com' + href
id = href.rstrip('/').split('/')[-1]
name = href.rstrip('/').split('/')[-2].replace('-', ' ').title()
profile = f'https://api.sofascore.app/api/v1/player/{id}/image'
# Create a dictionary for the player
player_info = {
'name': name,
'id': id,
'profile': profile,
'team': team_name,
'league': league,
'country': country,
'season': season,
'link': full_link
}
players_dic.append(player_info)
# Export to CSV
os.makedirs('data', exist_ok=True)
players_df = pd.DataFrame(players_dic)
players_df.to_csv('data/sofascore_players.csv', index=False, encoding='utf-8')
return players_dic
def get_players_from_team_ids(teams, delay=5, language='es'):
"""
Extracts player information from team URLs on Sofascore.
Args:
teams (list): List of dictionaries, each containing team details and URL.
delay (int): Time to wait (in seconds) between requests to avoid overloading the server. Default is 5 seconds.
Returns:
list: A list of dictionaries with player information.
"""
players_dic = [] # List to store player information
repeated = [] # List to keep track of processed links
for team in teams:
time.sleep(delay) # Respect the delay between requests
team_id = team
api_url = f'https://www.sofascore.com/api/v1/team/{team_id}'
data = request_to_json(api_url)
slug = data['team']['slug']
# Default language is Spanish
if language == 'es':
url = f'https://www.sofascore.com/es/equipo/futbol/{slug}/{team_id}'
else:
url = f'https://www.sofascore.com/team/football/{slug}/{team_id}'
# Make the request and parse the page content
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html.parser')
links = soup.find_all('a', href=True)
for link in links:
href = link['href']
if href not in repeated:
repeated.append(href)
if '/es/jugador/' in href:
full_link = 'https://www.sofascore.com' + href
id = href.rstrip('/').split('/')[-1]
name = href.rstrip('/').split('/')[-2].replace('-', ' ').title()
profile = f'https://api.sofascore.app/api/v1/player/{id}/image'
# Create a dictionary for the player
player_info = {
'name': name,
'id': id,
'profile': profile,
'team_id': team_id,
'team_name': data['team']['name'],
'link': full_link
}
players_dic.append(player_info)
# Export to CSV
os.makedirs('data', exist_ok=True)
players_df = pd.DataFrame(players_dic)
players_df.to_csv('data/sofascore_players.csv', index=False, encoding='utf-8')
return players_dic
def get_heatmap_from_players(players, delay=5):
"""
Fetches heatmap data for a list of players from Sofascore API.
Args:
players (list of dict): List of player dictionaries with 'player_id'.
delay (int): Delay in seconds between API requests to avoid rate limiting.
Returns:
DataFrame: Combined heatmap data for all players and tournaments.
"""
dfs = []
for player in players:
time.sleep(delay)
player_id = player['id']
# Get tournaments for the current player
try:
tournaments = get_player_tournaments(player_id)
except:
continue
# Loop through each tournament
for _, row in tournaments.iterrows():
league_id = row['tournaments_id']
season_id = row['season_id']
# Get heatmap for the current player, league, and season
try:
heatmap_tournament = get_heatmap(player_id, league_id, season_id)
dfs.append(heatmap_tournament)
except:
continue
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True)
heatmaps_df = pd.concat(dfs, ignore_index=True)
heatmaps_df.to_csv('data/sofascore_heatmap.csv', index=False, encoding='utf-8')
else:
heatmaps_df = pd.DataFrame()
print("No heatmap data was collected.")
return heatmaps_df
def get_lineups_from_events(events, delay=5):
"""
Processes a list of events to extract and organize lineup data and average player positions.
Args:
events (list): List of dictionaries containing event information.
delay (int): Time to wait (in seconds) between requests to avoid overloading the server. Default is 5 seconds.
Returns:
pd.DataFrame: A DataFrame containing the lineup data and average player positions for all processed events.
"""
dfs = [] # Initialize a list to store DataFrames for each event
for i in range(len(events)):
time.sleep(delay) # Wait before making the next request
event = re.search(r'id:(\d+)', events[i]['link'])
event_id = event.group(1) if event else 'unknown'
try:
data = get_event_data(event_id)
status = data['event']['status']['type']
if status == 'finished':
# Get lineup, average positions, and event data
lineups = get_lineups(event_id)
average_positions = get_average_positions(event_id)
# Extract and process formations for home and away teams
home_formation = lineups['home']['formation']
away_formation = lineups['away']['formation']
# Process home formation
home_groups_formation = home_formation.split('-')
home_def = int(home_groups_formation[0])
home_ata = int(home_groups_formation[-1])
if len(home_groups_formation) == 4:
home_mid_0 = int(home_groups_formation[1])
home_mid_1 = 0
home_mid_2 = int(home_groups_formation[2])
else:
home_mid_0 = 0
home_mid_1 = int(home_groups_formation[1])
home_mid_2 = 0
# Process away formation
away_groups_formation = away_formation.split('-')
away_def = int(away_groups_formation[0])
away_ata = int(away_groups_formation[-1])
if len(away_groups_formation) == 4:
away_mid_0 = int(away_groups_formation[1])
away_mid_1 = 0
away_mid_2 = int(away_groups_formation[2])
else:
away_mid_0 = 0
away_mid_1 = int(away_groups_formation[1])
away_mid_2 = 0
# Initialize lists to store player data
home = []
away = []
home_avg = []
away_avg = []
# Process home team players
for j in range(len(lineups['home']['players'])):
player = lineups['home']['players'][j]
name = player['player']['name']
id = player['player']['id']
jersey = player['shirtNumber']
position = player.get('position', '')
substitute = player['substitute']
minutes = player.get('statistics', {}).get('minutesPlayed', 0)
if j < len(average_positions['home']):
avg_player = average_positions['home'][j]
avg_id = avg_player['player']['id']
averageX = avg_player['averageX']
averageY = avg_player['averageY']
pointsCount = avg_player['pointsCount']
order = j + 1
line, lat, pos = determine_position(order, home_def, home_mid_0, home_mid_1, home_mid_2, home_ata, substitute)
# Append player data to home list
home.append([name, id, jersey, position, substitute, minutes, order, line, lat, pos])
home_avg.append([avg_id, averageX, averageY, pointsCount])
# Process away team players
for k in range(len(lineups['away']['players'])):
player = lineups['away']['players'][k]
name = player['player']['name']
id = player['player']['id']
jersey = player['shirtNumber']
position = player.get('position', '')
substitute = player['substitute']
minutes = player.get('statistics', {}).get('minutesPlayed', 0)
if k < len(average_positions['away']):
avg_player = average_positions['away'][k]
avg_id = avg_player['player']['id']
averageX = avg_player['averageX']
averageY = avg_player['averageY']
pointsCount = avg_player['pointsCount']
order = k + 1
line, lat, pos = determine_position(order, away_def, away_mid_0, away_mid_1, away_mid_2, away_ata, substitute)
# Append player data to away list
away.append([name, id, jersey, position, substitute, minutes, order, line, lat, pos])
away_avg.append([avg_id, averageX, averageY, pointsCount])
# Create DataFrames for home and away teams
home_df = pd.DataFrame(home, columns=['player', 'id', 'jersey', 'position', 'substitute', 'minutes', 'order', 'line', 'lat', 'pos'])
home_df['local'] = 'Home'
home_df['team'] = data['event']['homeTeam']['shortName']
home_df['formation'] = home_formation
home_df['defense'] = home_def
home_df['midfield'] = home_mid_0 + home_mid_1 + home_mid_2
home_df['attack'] = home_ata
away_df = pd.DataFrame(away, columns=['player', 'id', 'jersey', 'position', 'substitute', 'minutes', 'order', 'line', 'lat', 'pos'])
away_df['local'] = 'Away'
away_df['team'] = data['event']['awayTeam']['shortName']
away_df['formation'] = away_formation
away_df['defense'] = away_def
away_df['midfield'] = away_mid_0 + away_mid_1 + away_mid_2
away_df['attack'] = away_ata
# Create DataFrame for average player positions
home_avg_position = pd.DataFrame(home_avg, columns=['avg_id', 'averageX', 'averageY', 'pointsCount'])
away_avg_position = pd.DataFrame(away_avg, columns=['avg_id', 'averageX', 'averageY', 'pointsCount'])
df_avg_position = pd.concat([home_avg_position, away_avg_position], ignore_index=True)
df_avg_position.rename(columns={'avg_id': 'id'}, inplace=True)
# Merge lineup data with average position data
df = pd.concat([home_df, away_df], ignore_index=True)
df_merged = pd.merge(df, df_avg_position, on='id', how='left')
# Append the DataFrame to the list
dfs.append(df_merged)
except Exception as e:
print(f"Error in processing lineup for event {event_id}: {e}")
# Concatenate all DataFrames into one and save to CSV
os.makedirs('data', exist_ok=True)
lineups_df = pd.concat(dfs, ignore_index=True)
lineups_df.to_csv('data/sofascore_lineup.csv', index=False, encoding='utf-8')
return lineups_df
def get_results_from_events(events, delay=5):
"""
Extracts match results from a list of events and returns a DataFrame.
Args:
events (list): A list of event dictionaries, each containing an 'id'.
delay (int, optional): Delay in seconds between requests. Default is 5 seconds.
Returns:
pd.DataFrame: A DataFrame containing match results for each event.
"""
# List to store DataFrames for each event
dfs = []
for event in events:
# Respect the delay between requests to avoid overloading the server
time.sleep(delay)
# Extract the event ID from the event dictionary
event_id = event['id']
# Fetch event data using the event ID
event_data = get_event_data(event_id)
status = event_data['event']['status']['type']
if status == 'finished':
# Extract necessary details from the event data
homeTeam_name = event_data['event']['homeTeam']['shortName']
homeTeam_id = event_data['event']['homeTeam']['id']
homeScore = int(event_data['event']['homeScore']['display'])
awayTeam_name = event_data['event']['awayTeam']['shortName']
awayTeam_id = event_data['event']['awayTeam']['id']
awayScore = int(event_data['event']['awayScore']['display'])
# Create a dictionary for the home team
home_dic = {
'event_id': event_id,
'team': homeTeam_name,
'team_id': homeTeam_id,
'score_for': homeScore,
'score_against': awayScore,
'win': homeScore > awayScore,
'draw': homeScore == awayScore,
'loose': homeScore < awayScore,
'local': 'Home'
}
# Create a dictionary for the away team
away_dic = {
'event_id': event_id,
'team': awayTeam_name,
'team_id': awayTeam_id,
'score_for': awayScore,
'score_against': homeScore,
'win': awayScore > homeScore,
'draw': awayScore == homeScore,
'loose': awayScore < homeScore,
'local': 'Away'
}
# Convert the dictionaries into DataFrames
home_df = pd.DataFrame([home_dic])
away_df = pd.DataFrame([away_dic])
# Concatenate the home and away DataFrames into a single DataFrame
df = pd.concat([home_df, away_df], ignore_index=True)
# Append the DataFrame to the list
dfs.append(df)
# Concatenate all the DataFrames into one final DataFrame
results_df = pd.concat(dfs, ignore_index=True)
# Export the final DataFrame to a CSV file
os.makedirs('data', exist_ok=True)
results_df.to_csv('data/sofascore_results.csv', index=False, encoding='utf-8')
return results_df
def get_attributes_from_players(players, delay=5):
"""
Fetches attributes data for a list of players from Sofascore API.
Args:
players (list of dict): List of player dictionaries with 'player_id'.
delay (int): Delay in seconds between API requests to avoid rate limiting.
Returns:
DataFrame: Combined attributes data for all players and tournaments.
"""
dfs = []
for player in players:
time.sleep(delay)
player_id = player['id']
# Get attributes for the current player
try:
attributes = get_player_attributes(player_id)
dfs.append(attributes)
except:
continue
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True)
attributes_df = pd.concat(dfs, ignore_index=True)
attributes_df.to_csv('data/sofascore_attributes.csv', index=False, encoding='utf-8')
else:
attributes_df = pd.DataFrame()
print("No attributes data was collected.")
return attributes_df
def get_statistics_from_players(players, league_id, season_id, delay=5):
"""
Fetches statistics data for a list of players from the Sofascore API.
Args:
players (list of dict): List of player dictionaries with 'id' key for player IDs.
league_id (str): The league identifier for the statistics.
season_id (str): The season identifier for the statistics.
delay (int): Delay in seconds between API requests to avoid rate limiting.
save_path (str): Path to save the resulting DataFrame as a CSV file.
Returns:
DataFrame: Combined statistics data for all players, or empty DataFrame if none collected.
"""
dfs = []
for player in players:
time.sleep(delay)
player_id = player['id']
# Get statistics for the current player
try:
statistics = get_player_statistics(player_id, league_id, season_id)
dfs.append(statistics)
except:
continue
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True)
statistics_df = pd.concat(dfs, ignore_index=True)
statistics_df.to_csv('data/sofascore_players_statistics.csv', index=False, encoding='utf-8')
else:
statistics_df = pd.DataFrame()
print("No statistics data was collected.")
return statistics_df
def get_statistics_from_events(events, delay=5):
"""
Fetches statistics data for a list of events from the Sofascore API.
Args:
events (list of dict): List of events.
Returns:
DataFrame: Combined statistics data for all events, or an empty DataFrame if none collected.
"""
dfs = []
for event in events:
time.sleep(delay) # Wait for the specified delay before making the next request
event_id = event
# Get statistics for the current event
try:
statistics = get_event_statistics(event_id) # Call the function to get statistics
dfs.append(statistics) # Append the statistics DataFrame to the list
except Exception as e:
print(f"Error retrieving statistics for event {event_id}: {e}")
continue # Continue to the next event if there's an error
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True) # Create the directory if it doesn't exist
statistics_df = pd.concat(dfs, ignore_index=True) # Concatenate all DataFrames
statistics_df.to_csv('data/sofascore_events_statistics.csv', index=False, encoding='utf-8') # Save to CSV
else:
statistics_df = pd.DataFrame() # Return an empty DataFrame if no data was collected
print("No statistics data was collected.")
return statistics_df
def get_momentum_from_events(events, delay=5):
"""
Fetches and combines momentum data for a list of events, with an optional delay between requests.
Args:
events (list): List of event IDs to fetch momentum data for.
delay (int, optional): Time in seconds to wait between API requests. Defaults to 5.
Returns:
pd.DataFrame: Combined DataFrame of momentum data for all events.
"""
dfs = []
for event in events:
time.sleep(delay)
event_id = event
# Attempt to fetch momentum for the current event
try:
momentum = get_momentum(event_id)
dfs.append(momentum)
except Exception as e:
print(f"Error retrieving momentum for event {event_id}: {e}")
continue
# Concatenate and save all DataFrames if data was collected
if dfs:
os.makedirs('data', exist_ok=True)
momentum_df = pd.concat(dfs, ignore_index=True)
momentum_df.to_csv('data/sofascore_momentum.csv', index=False, encoding='utf-8')
else:
momentum_df = pd.DataFrame()
print("No momentum data was collected.")
return momentum_df
def get_statistics_from_teams(teams, league_id, season_id, delay=5):
"""
Fetches statistics data for a list of teams from the Sofascore API.
Args:
teams (list of dict): List of team dictionaries with 'id' key for team IDs.
league_id (str): The league identifier for the statistics.
season_id (str): The season identifier for the statistics.
delay (int): Delay in seconds between API requests to avoid rate limiting.
save_path (str): Path to save the resulting DataFrame as a CSV file.
Returns:
DataFrame: Combined statistics data for all teams, or empty DataFrame if none collected.
"""
dfs = []
for team in teams:
time.sleep(delay)
team_id = team['id']
# Get statistics for the current team
try:
statistics = get_team_statistics(team_id, league_id, season_id)
dfs.append(statistics)
except:
continue
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True)
statistics_df = pd.concat(dfs, ignore_index=True)
statistics_df.to_csv('data/sofascore_teams_statistics.csv', index=False, encoding='utf-8')
else:
statistics_df = pd.DataFrame()
print("No statistics data was collected.")
return statistics_df
def get_statistics_from_team_ids(teams, league_id, season_id, delay=5):
"""
Fetches statistics data for a list of teams from the Sofascore API.
Args:
teams (list of dict): List of team dictionaries with 'id' key for team IDs.
league_id (str): The league identifier for the statistics.
season_id (str): The season identifier for the statistics.
delay (int): Delay in seconds between API requests to avoid rate limiting.
save_path (str): Path to save the resulting DataFrame as a CSV file.
Returns:
DataFrame: Combined statistics data for all teams, or empty DataFrame if none collected.
"""
dfs = []
for team in teams:
time.sleep(delay)
team_id = team
# Get statistics for the current team
try:
statistics = get_team_statistics(team_id, league_id, season_id)
dfs.append(statistics)
except:
continue
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True)
statistics_df = pd.concat(dfs, ignore_index=True)
statistics_df.to_csv('data/sofascore_teams_statistics.csv', index=False, encoding='utf-8')
else:
statistics_df = pd.DataFrame()
print("No statistics data was collected.")
return statistics_df
def get_highlights_from_events(events, delay=5):
"""
Fetches highlight data for a list of events from the Sofascore API.
Args:
events (list of dict): List of events.
Returns:
DataFrame: Combined highlight data for all events, or an empty DataFrame if none collected.
"""
dfs = []
for event in events:
time.sleep(delay) # Wait for the specified delay before making the next request
event_id = event
# Get highlight for the current event
try:
highlight = get_highlights(event_id) # Call the function to get highlight
dfs.append(highlight) # Append the highlight DataFrame to the list
except Exception as e:
print(f"Error retrieving highlight for event {event_id}: {e}")
continue # Continue to the next event if there's an error
# Concatenate all dataframes and save to CSV
if dfs:
os.makedirs('data', exist_ok=True) # Create the directory if it doesn't exist
highlight_df = pd.concat(dfs, ignore_index=True) # Concatenate all DataFrames
highlight_df.to_csv('data/sofascore_highlight.csv', index=False, encoding='utf-8') # Save to CSV
else:
highlight_df = pd.DataFrame() # Return an empty DataFrame if no data was collected
print("No highlight data was collected.")
return highlight_df
def get_groups_from_league(league_id, season_id):
"""
Fetches and saves standings for each group in a specified league and season as separate CSV files.
Args:
league_id (str): Unique identifier for the league.
season_id (str): Unique identifier for the season.
Returns:
DataFrame: Combined DataFrame of the last processed group standings.
"""
# API endpoint for league standings
api_url = f'https://www.sofascore.com/api/v1/unique-tournament/{league_id}/season/{season_id}/standings/total'
# Fetch data from API
data = request_to_json(api_url)
column_names = ['Equipo', 'Pos', 'PJ', 'PG', 'GA', 'GC', 'PP', 'PE', 'Pts', 'Dif', 'team_id', 'Escudo']
dfs = []
# Process each group in standings
for i in range(len(data['standings'])):
group_df = pd.DataFrame(data['standings'][i]['rows'])
# Extract team ID and logo URL
group_df['team_id'] = group_df['team'].apply(lambda x: x['id'] if isinstance(x, dict) else None)
group_df['Escudo'] = group_df['team_id'].apply(lambda x: f'https://api.sofascore.app/api/v1/team/{x}/image' if x else None)
group_df['team'] = group_df['team'].apply(lambda x: x['name'] if isinstance(x, dict) else None)
# Drop unnecessary columns and rename
group_df = group_df.drop(columns=['descriptions', 'promotion', 'id'])
group_df.columns = column_names
# Save group data to CSV
letter = chr(65 + i)
group_df.to_csv(f'data/sofascore_group_{letter}.csv', index=False, encoding='utf-8')
dfs.append(group_df)
return dfs
def get_shotmap_from_events(events, delay=5):
"""
Fetches and combines shotmap data for a list of events, with an optional delay between requests.
Args:
events (list): List of event IDs to fetch shotmap data for.
delay (int, optional): Time in seconds to wait between API requests. Defaults to 5.
Returns:
pd.DataFrame: Combined DataFrame of shotmap data for all events.
"""
dfs = []
for event in events:
time.sleep(delay)
event_id = event
# Attempt to fetch shotmap for the current event
try:
shotmap = get_shotmap(event_id)
dfs.append(shotmap)
except Exception as e:
print(f"Error retrieving shotmap for event {event_id}: {e}")
continue
# Concatenate and save all DataFrames if data was collected
if dfs:
os.makedirs('data', exist_ok=True)
shotmap_df = pd.concat(dfs, ignore_index=True)
shotmap_df.to_csv('data/sofascore_shotmap.csv', index=False, encoding='utf-8')
else:
shotmap_df = pd.DataFrame()
print("No shotmap data was collected.")
return shotmap_df
def get_profile_from_players(players, delay=5):
"""
Collects profiles of multiple players and saves the data to a CSV file.
Args:
players (list): A list of dictionaries, each containing a 'link' key with the player's URL.
Returns:
DataFrame: A pandas DataFrame containing the collected player profiles.
"""
dfs = []
for player in players:
time.sleep(delay)
player_url = player['link']
player_data = get_player_profile(player_url)
dfs.append(player_data)
if dfs:
# Create a directory to store the data
os.makedirs('data', exist_ok=True)
# Convert the data into a DataFrame and save it as a CSV file
player_profile_df = pd.DataFrame(dfs)
player_profile_df.to_csv('data/sofascore_player_profile.csv', index=False, encoding='utf-8')
else:
player_profile_df = pd.DataFrame()
print("No player profile was collected.")
return player_profile_df
def get_incidents_from_events(events, delay=5):
"""
Fetches incident data for a list of events from the Sofascore API.
Args:
events (list of dict): List of events.
Returns:
DataFrame: Combined incident data for all events, or an empty DataFrame if none collected.
"""
dfs = []