python-espncricinfo 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- espncricinfo/__init__.py +1 -0
- espncricinfo/_core.py +60 -0
- espncricinfo/exceptions.py +25 -0
- espncricinfo/match.py +693 -0
- espncricinfo/match_ref.py +79 -0
- espncricinfo/player.py +177 -0
- espncricinfo/py.typed +0 -0
- espncricinfo/seasons.py +95 -0
- espncricinfo/series.py +128 -0
- espncricinfo/summary.py +34 -0
- espncricinfo/teams.py +106 -0
- python_espncricinfo-1.0.0.dist-info/METADATA +166 -0
- python_espncricinfo-1.0.0.dist-info/RECORD +15 -0
- python_espncricinfo-1.0.0.dist-info/WHEEL +4 -0
- python_espncricinfo-1.0.0.dist-info/licenses/LICENSE.txt +22 -0
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
"""Lightweight (series_id, match_id) references."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import TYPE_CHECKING, Any
|
|
7
|
+
|
|
8
|
+
from espncricinfo._core import reference_ids
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
12
|
+
|
|
13
|
+
from espncricinfo.match import Match
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class MatchRef:
|
|
18
|
+
"""A lightweight reference to an ESPN Cricinfo match.
|
|
19
|
+
|
|
20
|
+
Stores the ``series_id`` and ``match_id`` needed to construct a
|
|
21
|
+
:class:`~espncricinfo.match.Match`. Supports dict and CSV serialization
|
|
22
|
+
and tuple unpacking for backward compatibility.
|
|
23
|
+
|
|
24
|
+
Example::
|
|
25
|
+
|
|
26
|
+
from espncricinfo.match_ref import MatchRef
|
|
27
|
+
|
|
28
|
+
ref = MatchRef(series_id=1478874, match_id=1478914)
|
|
29
|
+
series_id, match_id = ref # tuple unpacking still works
|
|
30
|
+
m = ref.to_match() # hydrate a full Match object
|
|
31
|
+
d = ref.to_dict() # {"series_id": 1478874, "match_id": 1478914}
|
|
32
|
+
row = ref.to_csv_row() # ["1478874", "1478914"]
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
series_id: int
|
|
36
|
+
match_id: int
|
|
37
|
+
|
|
38
|
+
def __post_init__(self) -> None:
|
|
39
|
+
"""Coerce both ids to int."""
|
|
40
|
+
object.__setattr__(self, "series_id", int(self.series_id))
|
|
41
|
+
object.__setattr__(self, "match_id", int(self.match_id))
|
|
42
|
+
|
|
43
|
+
def __iter__(self) -> Iterator[int]:
|
|
44
|
+
"""Yield series_id then match_id — enables tuple unpacking."""
|
|
45
|
+
yield self.series_id
|
|
46
|
+
yield self.match_id
|
|
47
|
+
|
|
48
|
+
def to_dict(self) -> dict[str, int]:
|
|
49
|
+
"""Return ``{"series_id": int, "match_id": int}``."""
|
|
50
|
+
return {"series_id": self.series_id, "match_id": self.match_id}
|
|
51
|
+
|
|
52
|
+
@classmethod
|
|
53
|
+
def from_dict(cls, d: Mapping[str, Any]) -> MatchRef:
|
|
54
|
+
"""Construct from a mapping with ``series_id`` and ``match_id`` keys."""
|
|
55
|
+
return cls(series_id=d["series_id"], match_id=d["match_id"])
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def from_core_event_url(cls, url: str) -> MatchRef:
|
|
59
|
+
"""Construct from a core ESPN event reference."""
|
|
60
|
+
series_id, match_id = reference_ids(url, "events")
|
|
61
|
+
return cls(series_id=series_id, match_id=match_id)
|
|
62
|
+
|
|
63
|
+
def to_csv_row(self) -> list[str]:
|
|
64
|
+
"""Return ``[str(series_id), str(match_id)]`` for use with ``csv.writer``."""
|
|
65
|
+
return [str(self.series_id), str(self.match_id)]
|
|
66
|
+
|
|
67
|
+
@classmethod
|
|
68
|
+
def from_csv_row(cls, row: Sequence[str | int]) -> MatchRef:
|
|
69
|
+
"""Construct from a 2-element sequence ``[series_id, match_id]``."""
|
|
70
|
+
return cls(series_id=int(row[0]), match_id=int(row[1]))
|
|
71
|
+
|
|
72
|
+
def to_match(self) -> Match:
|
|
73
|
+
"""Hydrate a full :class:`~espncricinfo.match.Match` object.
|
|
74
|
+
|
|
75
|
+
Triggers a Playwright fetch — use only when you need full match data.
|
|
76
|
+
"""
|
|
77
|
+
from espncricinfo.match import Match
|
|
78
|
+
|
|
79
|
+
return Match(self.match_id, self.series_id)
|
espncricinfo/player.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
"""Player records from the ESPN core API and the Statsguru pages."""
|
|
2
|
+
|
|
3
|
+
import csv
|
|
4
|
+
from datetime import date
|
|
5
|
+
from functools import cached_property
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from bs4 import BeautifulSoup
|
|
10
|
+
|
|
11
|
+
from espncricinfo import _core
|
|
12
|
+
from espncricinfo.exceptions import PlayerNotFoundError
|
|
13
|
+
|
|
14
|
+
_ATHLETES = "http://core.espnuk.org/v2/sports/cricket/athletes"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Player:
|
|
18
|
+
"""A player, loaded from the ESPN core API athlete record.
|
|
19
|
+
|
|
20
|
+
Example values are for ``Player(277916)``, Ajinkya Rahane.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
#: ESPNcricinfo player id.
|
|
24
|
+
player_id: int
|
|
25
|
+
#: Name as printed on scorecards, ``'Ajinkya Rahane'``.
|
|
26
|
+
name: str
|
|
27
|
+
#: ``'Ajinkya'``.
|
|
28
|
+
first_name: str
|
|
29
|
+
#: ``'Ajinkya Madhukar Rahane'``.
|
|
30
|
+
full_name: str
|
|
31
|
+
#: Date of birth, or None if ESPN has none.
|
|
32
|
+
date_of_birth: date | None
|
|
33
|
+
#: Age in years as ESPN reports it, or None.
|
|
34
|
+
age: int | None
|
|
35
|
+
#: ``'Top-order batter'``, or None.
|
|
36
|
+
playing_role: str | None
|
|
37
|
+
#: ``'Right-hand bat'``, or None.
|
|
38
|
+
batting_style: str | None
|
|
39
|
+
#: ``'Right-arm medium'``, or None.
|
|
40
|
+
bowling_style: str | None
|
|
41
|
+
#: The core API athlete record.
|
|
42
|
+
json: dict[str, Any]
|
|
43
|
+
|
|
44
|
+
def __init__(self, player_id: int | str) -> None:
|
|
45
|
+
"""Load the player record.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
player_id: ESPNcricinfo player id (the number in a profile URL).
|
|
49
|
+
"""
|
|
50
|
+
self.player_id = int(player_id)
|
|
51
|
+
self.json = self._get_json()
|
|
52
|
+
record = self.json
|
|
53
|
+
self.name = record["name"]
|
|
54
|
+
self.first_name = record.get("firstName", "")
|
|
55
|
+
self.full_name = record.get("fullName", self.name)
|
|
56
|
+
born = record.get("dateOfBirth")
|
|
57
|
+
self.date_of_birth = date.fromisoformat(born[:10]) if born else None
|
|
58
|
+
self.age = record.get("age")
|
|
59
|
+
self.playing_role = (record.get("position") or {}).get("name")
|
|
60
|
+
styles = {
|
|
61
|
+
style.get("type"): style.get("description")
|
|
62
|
+
for style in record.get("style") or []
|
|
63
|
+
}
|
|
64
|
+
self.batting_style = styles.get("batting")
|
|
65
|
+
self.bowling_style = styles.get("bowling")
|
|
66
|
+
|
|
67
|
+
def __str__(self) -> str:
|
|
68
|
+
"""Return the player's name."""
|
|
69
|
+
return self.name
|
|
70
|
+
|
|
71
|
+
def __repr__(self) -> str:
|
|
72
|
+
"""Return ``Player(player_id)``."""
|
|
73
|
+
return f"Player({self.player_id})"
|
|
74
|
+
|
|
75
|
+
def _get_json(self) -> dict[str, Any]:
|
|
76
|
+
response = _core.http_get(f"{_ATHLETES}/{self.player_id}")
|
|
77
|
+
if response.status_code == 404:
|
|
78
|
+
raise PlayerNotFoundError(f"Player not found: {self.player_id}")
|
|
79
|
+
response.raise_for_status()
|
|
80
|
+
return response.json()
|
|
81
|
+
|
|
82
|
+
@cached_property
|
|
83
|
+
def major_teams(self) -> list[str]:
|
|
84
|
+
"""Names of the player's major teams (one request per team, on first access)."""
|
|
85
|
+
teams = []
|
|
86
|
+
for reference in self.json.get("majorTeams", []):
|
|
87
|
+
response = _core.http_get(reference["$ref"])
|
|
88
|
+
response.raise_for_status()
|
|
89
|
+
team = response.json()
|
|
90
|
+
name = team.get("longName") or team.get("displayName") or team.get("name")
|
|
91
|
+
if name:
|
|
92
|
+
teams.append(name)
|
|
93
|
+
return teams
|
|
94
|
+
|
|
95
|
+
def _write_stats_table(self, query: str, table_index: int, file_name: str) -> None:
|
|
96
|
+
"""Write one table of the player's stats page to ``file_name`` as CSV.
|
|
97
|
+
|
|
98
|
+
Each row's cells are on separate lines in ESPN's HTML, so a row's text
|
|
99
|
+
split on newlines gives its cells (with an empty leading cell).
|
|
100
|
+
"""
|
|
101
|
+
url = (
|
|
102
|
+
"https://stats.espncricinfo.com/ci/engine/player/"
|
|
103
|
+
f"{self.player_id}.html?{query}"
|
|
104
|
+
)
|
|
105
|
+
response = _core.http_get(url)
|
|
106
|
+
soup = BeautifulSoup(response.text, "html.parser")
|
|
107
|
+
table = soup.find_all("table")[table_index]
|
|
108
|
+
rows = [tr.text.splitlines() for tr in table.find_all("tr")]
|
|
109
|
+
with Path(file_name).open("w", newline="") as csv_file:
|
|
110
|
+
csv.writer(csv_file).writerows(rows)
|
|
111
|
+
|
|
112
|
+
def get_career_averages(
|
|
113
|
+
self,
|
|
114
|
+
file_name: str | None = None,
|
|
115
|
+
match_format: int = 11,
|
|
116
|
+
data_type: str = "allround",
|
|
117
|
+
) -> None:
|
|
118
|
+
"""Write career averages (overall and by span) to a CSV file.
|
|
119
|
+
|
|
120
|
+
Args:
|
|
121
|
+
file_name: Output path. Defaults to
|
|
122
|
+
``{player_id}_{match_format}_{data_type}_career_averages.csv``.
|
|
123
|
+
match_format: 1 Test, 2 ODI, 3 T20I, 11 all international,
|
|
124
|
+
20 youth Test, 21 youth ODI.
|
|
125
|
+
data_type: ``allround``, ``batting``, ``bowling`` or ``fielding``.
|
|
126
|
+
"""
|
|
127
|
+
if file_name is None:
|
|
128
|
+
file_name = (
|
|
129
|
+
f"{self.player_id}_{match_format}_{data_type}_career_averages.csv"
|
|
130
|
+
)
|
|
131
|
+
query = f"class={match_format};template=results;type={data_type}"
|
|
132
|
+
self._write_stats_table(query, 2, file_name)
|
|
133
|
+
|
|
134
|
+
def get_career_summary(
|
|
135
|
+
self,
|
|
136
|
+
file_name: str | None = None,
|
|
137
|
+
match_format: int = 11,
|
|
138
|
+
data_type: str = "allround",
|
|
139
|
+
) -> None:
|
|
140
|
+
"""Write the career summary (one row per format, venue, opponent...) to CSV.
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
file_name: Output path. Defaults to
|
|
144
|
+
``{player_id}_{match_format}_{data_type}_career_summary.csv``.
|
|
145
|
+
match_format: 1 Test, 2 ODI, 3 T20I, 11 all international,
|
|
146
|
+
20 youth Test, 21 youth ODI.
|
|
147
|
+
data_type: ``allround``, ``batting``, ``bowling`` or ``fielding``.
|
|
148
|
+
"""
|
|
149
|
+
if file_name is None:
|
|
150
|
+
file_name = (
|
|
151
|
+
f"{self.player_id}_{match_format}_{data_type}_career_summary.csv"
|
|
152
|
+
)
|
|
153
|
+
query = f"class={match_format};template=results;type={data_type}"
|
|
154
|
+
self._write_stats_table(query, 3, file_name)
|
|
155
|
+
|
|
156
|
+
def get_data(
|
|
157
|
+
self,
|
|
158
|
+
file_name: str | None = None,
|
|
159
|
+
match_format: int = 11,
|
|
160
|
+
data_type: str = "allround",
|
|
161
|
+
view: str = "match",
|
|
162
|
+
) -> None:
|
|
163
|
+
"""Write the player's record match by match (or another view) to CSV.
|
|
164
|
+
|
|
165
|
+
Args:
|
|
166
|
+
file_name: Output path. Defaults to
|
|
167
|
+
``{player_id}_{match_format}_{data_type}_{view}.csv``.
|
|
168
|
+
match_format: 1 Test, 2 ODI, 3 T20I, 11 all international,
|
|
169
|
+
20 youth Test, 21 youth ODI.
|
|
170
|
+
data_type: ``allround``, ``batting``, ``bowling`` or ``fielding``.
|
|
171
|
+
view: ``match``, ``innings``, ``cumulative``, ``reverse_cumulative``,
|
|
172
|
+
``series``, ``tour`` or ``ground``.
|
|
173
|
+
"""
|
|
174
|
+
if file_name is None:
|
|
175
|
+
file_name = f"{self.player_id}_{match_format}_{data_type}_{view}.csv"
|
|
176
|
+
query = f"class={match_format};template=results;type={data_type};view={view}"
|
|
177
|
+
self._write_stats_table(query, 3, file_name)
|
espncricinfo/py.typed
ADDED
|
File without changes
|
espncricinfo/seasons.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Seasons of a series from the ESPN core API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from functools import cached_property
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from espncricinfo._core import collection_refs, get_json, reference_ids
|
|
10
|
+
from espncricinfo.exceptions import NoSeasonError
|
|
11
|
+
from espncricinfo.match_ref import MatchRef
|
|
12
|
+
from espncricinfo.teams import Team
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from espncricinfo.series import Series
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class Season:
|
|
19
|
+
"""One season of a series, with its teams and matches."""
|
|
20
|
+
|
|
21
|
+
#: Season id, usually the year.
|
|
22
|
+
id: int
|
|
23
|
+
#: ESPNcricinfo series (league) id.
|
|
24
|
+
series_id: int
|
|
25
|
+
#: Core API URL of the season.
|
|
26
|
+
url: str
|
|
27
|
+
#: ``2025``.
|
|
28
|
+
year: int
|
|
29
|
+
#: ``'Indian Premier League 2025'``.
|
|
30
|
+
name: str | None
|
|
31
|
+
#: Short name, or None.
|
|
32
|
+
short_name: str | None
|
|
33
|
+
#: Start of the season (UTC), or None.
|
|
34
|
+
start_date: datetime | None
|
|
35
|
+
#: End of the season (UTC), or None.
|
|
36
|
+
end_date: datetime | None
|
|
37
|
+
#: The core API season record.
|
|
38
|
+
json: dict[str, Any]
|
|
39
|
+
|
|
40
|
+
def __init__(self, season_id: int | str, series_id: int | str) -> None:
|
|
41
|
+
"""Load the season record.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
season_id: Season id, usually the year.
|
|
45
|
+
series_id: ESPNcricinfo series (league) id.
|
|
46
|
+
"""
|
|
47
|
+
self.id = int(season_id)
|
|
48
|
+
self.series_id = int(series_id)
|
|
49
|
+
self.url = (
|
|
50
|
+
"http://core.espnuk.org/v2/sports/cricket/leagues/"
|
|
51
|
+
f"{self.series_id}/seasons/{self.id}"
|
|
52
|
+
)
|
|
53
|
+
self.json = get_json(self.url, NoSeasonError)
|
|
54
|
+
self.year = int(self.json.get("year", self.id))
|
|
55
|
+
self.name = self.json.get("name")
|
|
56
|
+
self.short_name = self.json.get("shortName")
|
|
57
|
+
self.start_date = _parse_date(self.json.get("startDate"))
|
|
58
|
+
self.end_date = _parse_date(self.json.get("endDate"))
|
|
59
|
+
|
|
60
|
+
@classmethod
|
|
61
|
+
def from_reference(cls, url: str) -> Season:
|
|
62
|
+
"""Build a Season from a core API season URL."""
|
|
63
|
+
series_id, season_id = reference_ids(url, "seasons")
|
|
64
|
+
return cls(season_id, series_id)
|
|
65
|
+
|
|
66
|
+
@cached_property
|
|
67
|
+
def teams(self) -> list[Team]:
|
|
68
|
+
"""Teams in this season, loaded on first access (one request each)."""
|
|
69
|
+
urls = collection_refs(f"{self.url}/teams", NoSeasonError)
|
|
70
|
+
return [Team.from_reference(url) for url in urls]
|
|
71
|
+
|
|
72
|
+
@cached_property
|
|
73
|
+
def match_refs(self) -> list[MatchRef]:
|
|
74
|
+
"""MatchRefs for this season's matches, loaded on first access."""
|
|
75
|
+
urls = collection_refs(f"{self.url}/events", NoSeasonError)
|
|
76
|
+
return [MatchRef.from_core_event_url(url) for url in urls]
|
|
77
|
+
|
|
78
|
+
@cached_property
|
|
79
|
+
def series(self) -> Series:
|
|
80
|
+
"""The parent Series, loaded on first access."""
|
|
81
|
+
from espncricinfo.series import Series
|
|
82
|
+
|
|
83
|
+
return Series(self.series_id)
|
|
84
|
+
|
|
85
|
+
def __str__(self) -> str:
|
|
86
|
+
"""Return the season name, or its year."""
|
|
87
|
+
return self.name or str(self.year)
|
|
88
|
+
|
|
89
|
+
def __repr__(self) -> str:
|
|
90
|
+
"""Return a constructor-style summary."""
|
|
91
|
+
return f"Season(id={self.id}, series_id={self.series_id}, name={self.name!r})"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _parse_date(value: str | None) -> datetime | None:
|
|
95
|
+
return datetime.fromisoformat(value) if value else None
|
espncricinfo/series.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Series (ESPN "league") records from the ESPN core API."""
|
|
2
|
+
|
|
3
|
+
from functools import cached_property
|
|
4
|
+
from typing import Any
|
|
5
|
+
|
|
6
|
+
from espncricinfo import _core
|
|
7
|
+
from espncricinfo._core import collection_refs, get_json
|
|
8
|
+
from espncricinfo.exceptions import NoSeriesError
|
|
9
|
+
from espncricinfo.match_ref import MatchRef
|
|
10
|
+
from espncricinfo.seasons import Season
|
|
11
|
+
|
|
12
|
+
_LEAGUES = "http://core.espnuk.org/v2/sports/cricket/leagues"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Series:
|
|
16
|
+
"""A series or league, with its seasons, teams and matches.
|
|
17
|
+
|
|
18
|
+
Example values are for ``Series(1449924)``, the Indian Premier League.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
#: ESPNcricinfo series (league) id.
|
|
22
|
+
series_id: int
|
|
23
|
+
#: ``'Indian Premier League'``.
|
|
24
|
+
name: str
|
|
25
|
+
#: Short name, e.g. ``'IPL'``.
|
|
26
|
+
short_name: str
|
|
27
|
+
#: ESPN abbreviation.
|
|
28
|
+
abbreviation: str
|
|
29
|
+
#: URL slug.
|
|
30
|
+
slug: str
|
|
31
|
+
#: True for tournaments, False for bilateral series.
|
|
32
|
+
is_tournament: bool
|
|
33
|
+
#: ESPNcricinfo web page for the series.
|
|
34
|
+
url: str | None
|
|
35
|
+
#: Core API URLs of the series' seasons.
|
|
36
|
+
seasons: list[str]
|
|
37
|
+
#: Season years as strings, e.g. ``['2008', ..., '2025']``.
|
|
38
|
+
years: list[str]
|
|
39
|
+
#: The core API series record.
|
|
40
|
+
json: dict[str, Any]
|
|
41
|
+
|
|
42
|
+
def __init__(self, series_id: int | str) -> None:
|
|
43
|
+
"""Load the series record and its list of seasons.
|
|
44
|
+
|
|
45
|
+
Args:
|
|
46
|
+
series_id: ESPNcricinfo series (league) id.
|
|
47
|
+
"""
|
|
48
|
+
self.series_id = int(series_id)
|
|
49
|
+
self.json = self._get_json(f"{_LEAGUES}/{self.series_id}/")
|
|
50
|
+
self.name = self.json["name"]
|
|
51
|
+
self.short_name = self.json["shortName"]
|
|
52
|
+
self.abbreviation = self.json["abbreviation"]
|
|
53
|
+
self.slug = self.json["slug"]
|
|
54
|
+
self.is_tournament = bool(self.json.get("isTournament"))
|
|
55
|
+
links = self.json.get("links") or []
|
|
56
|
+
self.url = links[0]["href"] if links else None
|
|
57
|
+
self.seasons = collection_refs(
|
|
58
|
+
f"{_LEAGUES}/{self.series_id}/seasons", NoSeriesError
|
|
59
|
+
)
|
|
60
|
+
self.years = [ref.rstrip("/").rsplit("/", 1)[-1] for ref in self.seasons]
|
|
61
|
+
|
|
62
|
+
def _get_json(self, url: str) -> dict[str, Any]:
|
|
63
|
+
response = _core.http_get(url)
|
|
64
|
+
if response.status_code == 404:
|
|
65
|
+
raise NoSeriesError(f"Series not found: {self.series_id}")
|
|
66
|
+
response.raise_for_status()
|
|
67
|
+
return response.json()
|
|
68
|
+
|
|
69
|
+
def __str__(self) -> str:
|
|
70
|
+
"""Return the series name."""
|
|
71
|
+
return self.name
|
|
72
|
+
|
|
73
|
+
def __repr__(self) -> str:
|
|
74
|
+
"""Return ``Series(series_id)``."""
|
|
75
|
+
return f"Series({self.series_id})"
|
|
76
|
+
|
|
77
|
+
@cached_property
|
|
78
|
+
def events(self) -> list[dict[str, Any]]:
|
|
79
|
+
"""Core API event records for the series' first page of events.
|
|
80
|
+
|
|
81
|
+
One request per event, made on first access.
|
|
82
|
+
"""
|
|
83
|
+
refs = self._get_json(f"{_LEAGUES}/{self.series_id}/events").get("items", [])
|
|
84
|
+
return [self._get_json(item["$ref"]) for item in refs]
|
|
85
|
+
|
|
86
|
+
@cached_property
|
|
87
|
+
def season_objects(self) -> list[Season]:
|
|
88
|
+
"""Every season of the series, loaded on first access."""
|
|
89
|
+
return [Season.from_reference(url) for url in self.seasons]
|
|
90
|
+
|
|
91
|
+
@cached_property
|
|
92
|
+
def current_season(self) -> Season | None:
|
|
93
|
+
"""The season ESPN marks as current, or None."""
|
|
94
|
+
reference = (self.json.get("season") or {}).get("$ref")
|
|
95
|
+
return Season.from_reference(reference) if reference else None
|
|
96
|
+
|
|
97
|
+
@cached_property
|
|
98
|
+
def matches(self) -> list[MatchRef]:
|
|
99
|
+
"""MatchRefs for every match across all seasons, without duplicates."""
|
|
100
|
+
if self.seasons:
|
|
101
|
+
return list(
|
|
102
|
+
dict.fromkeys(
|
|
103
|
+
ref for season in self.season_objects for ref in season.match_refs
|
|
104
|
+
)
|
|
105
|
+
)
|
|
106
|
+
reference = (self.json.get("events") or {}).get("$ref")
|
|
107
|
+
urls = collection_refs(
|
|
108
|
+
reference or f"{_LEAGUES}/{self.series_id}/events", NoSeriesError
|
|
109
|
+
)
|
|
110
|
+
return [MatchRef.from_core_event_url(url) for url in urls]
|
|
111
|
+
|
|
112
|
+
@cached_property
|
|
113
|
+
def current_matches(self) -> list[MatchRef]:
|
|
114
|
+
"""Matches whose ESPN status is in progress (two requests per match)."""
|
|
115
|
+
active = []
|
|
116
|
+
for ref in self.matches:
|
|
117
|
+
event = get_json(
|
|
118
|
+
f"{_LEAGUES}/{ref.series_id}/events/{ref.match_id}", NoSeriesError
|
|
119
|
+
)
|
|
120
|
+
for competition in event.get("competitions", []):
|
|
121
|
+
status_url = (competition.get("status") or {}).get("$ref")
|
|
122
|
+
if status_url and (
|
|
123
|
+
get_json(status_url, NoSeriesError).get("type", {}).get("state")
|
|
124
|
+
== "in"
|
|
125
|
+
):
|
|
126
|
+
active.append(ref)
|
|
127
|
+
break
|
|
128
|
+
return active
|
espncricinfo/summary.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Recent-match listing."""
|
|
2
|
+
|
|
3
|
+
from datetime import date
|
|
4
|
+
|
|
5
|
+
from espncricinfo.match import Match
|
|
6
|
+
from espncricinfo.match_ref import MatchRef
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Summary:
|
|
10
|
+
"""Recent matches as :class:`~espncricinfo.match_ref.MatchRef` objects.
|
|
11
|
+
|
|
12
|
+
Uses Match.get_recent_matches() which scrapes the ESPN Cricinfo
|
|
13
|
+
results page via Playwright. Pass an optional date string (YYYY-MM-DD
|
|
14
|
+
or DD-MM-YYYY) to get matches for a specific day; defaults to today.
|
|
15
|
+
|
|
16
|
+
Example::
|
|
17
|
+
|
|
18
|
+
from espncricinfo.summary import Summary
|
|
19
|
+
|
|
20
|
+
for ref in Summary().matches:
|
|
21
|
+
m = ref.to_match()
|
|
22
|
+
print(m.description)
|
|
23
|
+
|
|
24
|
+
# Tuple unpacking also works:
|
|
25
|
+
for series_id, match_id in Summary().matches:
|
|
26
|
+
print(series_id, match_id)
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
#: The listed matches.
|
|
30
|
+
matches: list[MatchRef]
|
|
31
|
+
|
|
32
|
+
def __init__(self, date: date | str | None = None) -> None:
|
|
33
|
+
"""Fetch the results page for ``date`` (default: today)."""
|
|
34
|
+
self.matches = Match.get_recent_matches(date)
|
espncricinfo/teams.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
"""Teams within a series from the ESPN core API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from functools import cached_property
|
|
7
|
+
from typing import TYPE_CHECKING, Any
|
|
8
|
+
|
|
9
|
+
from espncricinfo._core import collection_refs, get_json, reference_ids
|
|
10
|
+
from espncricinfo.exceptions import NoTeamError
|
|
11
|
+
from espncricinfo.match_ref import MatchRef
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from espncricinfo.player import Player
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Team:
|
|
18
|
+
"""A team as it appears in one series."""
|
|
19
|
+
|
|
20
|
+
#: ESPNcricinfo team id.
|
|
21
|
+
id: int
|
|
22
|
+
#: ESPNcricinfo series (league) id.
|
|
23
|
+
series_id: int
|
|
24
|
+
#: Core API URL of the team within the series.
|
|
25
|
+
url: str
|
|
26
|
+
#: ``'Chennai Super Kings'``.
|
|
27
|
+
name: str | None
|
|
28
|
+
#: Abbreviation, e.g. ``'CSK'``.
|
|
29
|
+
short_name: str | None
|
|
30
|
+
#: Home location, or None.
|
|
31
|
+
location: str | None
|
|
32
|
+
#: Nickname, or None.
|
|
33
|
+
nickname: str | None
|
|
34
|
+
#: URL slug.
|
|
35
|
+
slug: str | None
|
|
36
|
+
#: Team color as hex, or None.
|
|
37
|
+
color: str | None
|
|
38
|
+
#: Logo URL, or None.
|
|
39
|
+
logo: str | None
|
|
40
|
+
#: True for national sides.
|
|
41
|
+
is_national: bool | None
|
|
42
|
+
#: True if ESPN marks the team active.
|
|
43
|
+
is_active: bool | None
|
|
44
|
+
#: Start of the team's linked match (UTC), or None.
|
|
45
|
+
match_date: datetime | None
|
|
46
|
+
#: The team's linked match in this series, or None.
|
|
47
|
+
match: MatchRef | None
|
|
48
|
+
#: The core API team record.
|
|
49
|
+
json: dict[str, Any]
|
|
50
|
+
|
|
51
|
+
def __init__(self, team_id: int | str, series_id: int | str) -> None:
|
|
52
|
+
"""Load the team record.
|
|
53
|
+
|
|
54
|
+
Args:
|
|
55
|
+
team_id: ESPNcricinfo team id.
|
|
56
|
+
series_id: ESPNcricinfo series (league) id.
|
|
57
|
+
"""
|
|
58
|
+
self.id = int(team_id)
|
|
59
|
+
self.series_id = int(series_id)
|
|
60
|
+
self.url = (
|
|
61
|
+
"http://core.espnuk.org/v2/sports/cricket/leagues/"
|
|
62
|
+
f"{self.series_id}/teams/{self.id}"
|
|
63
|
+
)
|
|
64
|
+
self.json = get_json(self.url, NoTeamError)
|
|
65
|
+
self.name = self.json.get("name")
|
|
66
|
+
self.short_name = self.json.get("abbreviation")
|
|
67
|
+
self.location = self.json.get("location")
|
|
68
|
+
self.nickname = self.json.get("nickname")
|
|
69
|
+
self.slug = self.json.get("slug")
|
|
70
|
+
self.color = self.json.get("color")
|
|
71
|
+
self.logo = next(
|
|
72
|
+
(logo["href"] for logo in self.json.get("logos", []) if "href" in logo),
|
|
73
|
+
None,
|
|
74
|
+
)
|
|
75
|
+
self.is_national = self.json.get("isNational")
|
|
76
|
+
self.is_active = self.json.get("isActive")
|
|
77
|
+
event = self.json.get("event") or {}
|
|
78
|
+
self.match_date = (
|
|
79
|
+
datetime.fromisoformat(event["date"]) if event.get("date") else None
|
|
80
|
+
)
|
|
81
|
+
self.match = (
|
|
82
|
+
MatchRef.from_core_event_url(event["$ref"]) if event.get("$ref") else None
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
@classmethod
|
|
86
|
+
def from_reference(cls, url: str) -> Team:
|
|
87
|
+
"""Build a Team from a core API team URL."""
|
|
88
|
+
series_id, team_id = reference_ids(url, "teams")
|
|
89
|
+
return cls(team_id, series_id)
|
|
90
|
+
|
|
91
|
+
@cached_property
|
|
92
|
+
def players(self) -> list[Player]:
|
|
93
|
+
"""The squad as Players, loaded on first access (one request each)."""
|
|
94
|
+
from espncricinfo.player import Player
|
|
95
|
+
|
|
96
|
+
athletes = self.json.get("athletes") or {}
|
|
97
|
+
if not athletes.get("$ref"):
|
|
98
|
+
return []
|
|
99
|
+
return [
|
|
100
|
+
Player(int(url.rstrip("/").rsplit("/", 1)[-1]))
|
|
101
|
+
for url in collection_refs(athletes["$ref"], NoTeamError)
|
|
102
|
+
]
|
|
103
|
+
|
|
104
|
+
def __repr__(self) -> str:
|
|
105
|
+
"""Return a constructor-style summary."""
|
|
106
|
+
return f"Team(id={self.id}, series_id={self.series_id}, name={self.name!r})"
|