python-espncricinfo 1.0.1__tar.gz → 1.2.0__tar.gz
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.
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/PKG-INFO +33 -13
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/README.md +26 -5
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/exceptions.py +4 -0
- python_espncricinfo-1.2.0/espncricinfo/grounds.py +53 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/match.py +223 -56
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/seasons.py +11 -1
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/series.py +36 -1
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/pyproject.toml +8 -10
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/pyproject.toml.orig +6 -7
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/LICENSE.txt +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/__init__.py +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/_core.py +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/match_ref.py +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/player.py +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/py.typed +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/summary.py +0 -0
- {python_espncricinfo-1.0.1 → python_espncricinfo-1.2.0}/espncricinfo/teams.py +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-espncricinfo
|
|
3
|
-
Version: 1.0
|
|
3
|
+
Version: 1.2.0
|
|
4
4
|
Summary: Python client for ESPNcricinfo match, series, season, team and player data
|
|
5
5
|
Keywords: espncricinfo,cricket,t20,odi,test cricket,scorecard,sports data
|
|
6
6
|
Author: Derek Willis, Gaurav Sood
|
|
7
|
-
Author-email: Derek Willis <dwillis@gmail.com
|
|
7
|
+
Author-email: Derek Willis <dwillis@gmail.com>
|
|
8
8
|
License-Expression: MIT
|
|
9
9
|
License-File: LICENSE.txt
|
|
10
10
|
Classifier: Development Status :: 4 - Beta
|
|
@@ -13,17 +13,16 @@ Classifier: Intended Audience :: Science/Research
|
|
|
13
13
|
Classifier: Operating System :: OS Independent
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
15
15
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
16
|
-
Classifier: Programming Language :: Python :: 3.12
|
|
17
16
|
Classifier: Programming Language :: Python :: 3.13
|
|
18
17
|
Classifier: Programming Language :: Python :: 3.14
|
|
19
18
|
Classifier: Topic :: Internet :: WWW/HTTP
|
|
20
19
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
-
Requires-Dist: requests
|
|
22
|
-
Requires-Dist: beautifulsoup4
|
|
23
|
-
Requires-Dist: dateparser
|
|
24
|
-
Requires-Dist: lxml
|
|
20
|
+
Requires-Dist: requests>=2.32.2
|
|
21
|
+
Requires-Dist: beautifulsoup4>=4.12.3
|
|
22
|
+
Requires-Dist: dateparser>=1.2.1
|
|
23
|
+
Requires-Dist: lxml>=5.3.0
|
|
25
24
|
Requires-Dist: playwright>=1.48.0
|
|
26
|
-
Requires-Python: >=3.
|
|
25
|
+
Requires-Python: >=3.13
|
|
27
26
|
Project-URL: Homepage, https://github.com/outside-edge/python-espncricinfo
|
|
28
27
|
Project-URL: Repository, https://github.com/outside-edge/python-espncricinfo
|
|
29
28
|
Project-URL: Documentation, https://outside-edge.github.io/python-espncricinfo/
|
|
@@ -45,7 +44,7 @@ A Python client for ESPNcricinfo match, series, season, team and player data.
|
|
|
45
44
|
|
|
46
45
|
## Description
|
|
47
46
|
|
|
48
|
-
Match pages are loaded with Playwright (WebKit), because ESPN's CDN refuses plain HTTP clients; player, series, season and team records come from ESPN's core JSON API. A `Match` needs
|
|
47
|
+
Match pages are loaded with Playwright (WebKit), because ESPN's CDN refuses plain HTTP clients; player, series, season and team records come from ESPN's core JSON API. A `Match` needs only a `match_id`; `Match.get_recent_matches()` and `Series(...).matches` list them.
|
|
49
48
|
|
|
50
49
|
Disclaimer: This library is not intended for commercial use and neither it nor its creator has any affiliation with ESPNCricInfo. The [LICENSE](https://github.com/outside-edge/python-espncricinfo/blob/master/LICENSE.txt) for this library applies only to the code, not to the data.
|
|
51
50
|
|
|
@@ -83,14 +82,14 @@ MatchRef(series_id=1523975, match_id=1523981)
|
|
|
83
82
|
>>> series_id, match_id = refs[0] # MatchRefs unpack like tuples
|
|
84
83
|
```
|
|
85
84
|
|
|
86
|
-
`Summary(date=...)`
|
|
85
|
+
For one day only, `Match.get_matches_on("2026-10-20")` keeps the matches played that day, multi-day matches included on each of their days. `Summary(date=...).matches` is the two-week window from `Match.get_recent_matches`, not one day.
|
|
87
86
|
|
|
88
87
|
## A single match
|
|
89
88
|
|
|
90
|
-
A match needs
|
|
89
|
+
A match needs only its match ID, the number in a match page URL. Passing the series ID too (`Match(1478914, 1478874)`, or `MatchRef.to_match()`) skips a redirect. Loading a match starts a headless WebKit browser.
|
|
91
90
|
|
|
92
91
|
```python
|
|
93
|
-
>>> m = Match(1478914
|
|
92
|
+
>>> m = Match(1478914)
|
|
94
93
|
>>> m.description
|
|
95
94
|
'IND Women v AUS Women'
|
|
96
95
|
>>> m.match_class
|
|
@@ -103,7 +102,19 @@ A match needs both its match ID and series ID: the two numbers in a match page U
|
|
|
103
102
|
('D Brown', 0)
|
|
104
103
|
```
|
|
105
104
|
|
|
106
|
-
|
|
105
|
+
To work through every match of a format, list a year's match IDs from Statsguru (1 Test, 2 ODI, 3 T20I, 8/9/10 the women's formats) and load each one. Each load starts a browser, so a year of Tests takes a minute or two:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
>>> ids = Match.get_match_ids(2023, 1)
|
|
109
|
+
>>> len(ids)
|
|
110
|
+
34
|
|
111
|
+
>>> Match(ids[0]).description
|
|
112
|
+
'New Zealand v Pakistan'
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
`batting_scorecard` and `bowling_scorecard` hold one list per innings and one dict per player. `over_by_over` gives runs and wickets for every over, and each `m.innings` entry has `fours` and `sixes`.
|
|
116
|
+
|
|
117
|
+
`m.ground` loads the ground record (`Ground` in `espncricinfo.grounds`): name, city, country, capacity.
|
|
107
118
|
|
|
108
119
|
## Players
|
|
109
120
|
|
|
@@ -133,6 +144,15 @@ The player ID is the number at the end of a player's profile URL.
|
|
|
133
144
|
'Chennai Super Kings'
|
|
134
145
|
```
|
|
135
146
|
|
|
147
|
+
Seasons that cross New Year, like the Big Bash League's, each have their own series ID. Look one up by the label ESPNcricinfo shows:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
>>> bbl = Series(8044)
|
|
151
|
+
>>> season = bbl.season("2024/25") # also 2024, "2024-25" or "2024/2025"
|
|
152
|
+
>>> season.label, season.series_id
|
|
153
|
+
('2024/25', 1443056)
|
|
154
|
+
```
|
|
155
|
+
|
|
136
156
|
`series.season_objects` lists every season and `season.match_refs` that season's matches. `series.matches` collects MatchRefs across all seasons (1,254 for the IPL), and `series.current_matches` keeps those in progress. `team.players` loads the squad on demand. ESPN's records for some bilateral tours are incomplete, for example listing one team for a two-team series.
|
|
137
157
|
|
|
138
158
|
<!-- USAGE-END -->
|
|
@@ -12,7 +12,7 @@ A Python client for ESPNcricinfo match, series, season, team and player data.
|
|
|
12
12
|
|
|
13
13
|
## Description
|
|
14
14
|
|
|
15
|
-
Match pages are loaded with Playwright (WebKit), because ESPN's CDN refuses plain HTTP clients; player, series, season and team records come from ESPN's core JSON API. A `Match` needs
|
|
15
|
+
Match pages are loaded with Playwright (WebKit), because ESPN's CDN refuses plain HTTP clients; player, series, season and team records come from ESPN's core JSON API. A `Match` needs only a `match_id`; `Match.get_recent_matches()` and `Series(...).matches` list them.
|
|
16
16
|
|
|
17
17
|
Disclaimer: This library is not intended for commercial use and neither it nor its creator has any affiliation with ESPNCricInfo. The [LICENSE](https://github.com/outside-edge/python-espncricinfo/blob/master/LICENSE.txt) for this library applies only to the code, not to the data.
|
|
18
18
|
|
|
@@ -50,14 +50,14 @@ MatchRef(series_id=1523975, match_id=1523981)
|
|
|
50
50
|
>>> series_id, match_id = refs[0] # MatchRefs unpack like tuples
|
|
51
51
|
```
|
|
52
52
|
|
|
53
|
-
`Summary(date=...)`
|
|
53
|
+
For one day only, `Match.get_matches_on("2026-10-20")` keeps the matches played that day, multi-day matches included on each of their days. `Summary(date=...).matches` is the two-week window from `Match.get_recent_matches`, not one day.
|
|
54
54
|
|
|
55
55
|
## A single match
|
|
56
56
|
|
|
57
|
-
A match needs
|
|
57
|
+
A match needs only its match ID, the number in a match page URL. Passing the series ID too (`Match(1478914, 1478874)`, or `MatchRef.to_match()`) skips a redirect. Loading a match starts a headless WebKit browser.
|
|
58
58
|
|
|
59
59
|
```python
|
|
60
|
-
>>> m = Match(1478914
|
|
60
|
+
>>> m = Match(1478914)
|
|
61
61
|
>>> m.description
|
|
62
62
|
'IND Women v AUS Women'
|
|
63
63
|
>>> m.match_class
|
|
@@ -70,7 +70,19 @@ A match needs both its match ID and series ID: the two numbers in a match page U
|
|
|
70
70
|
('D Brown', 0)
|
|
71
71
|
```
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
To work through every match of a format, list a year's match IDs from Statsguru (1 Test, 2 ODI, 3 T20I, 8/9/10 the women's formats) and load each one. Each load starts a browser, so a year of Tests takes a minute or two:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
>>> ids = Match.get_match_ids(2023, 1)
|
|
77
|
+
>>> len(ids)
|
|
78
|
+
34
|
|
79
|
+
>>> Match(ids[0]).description
|
|
80
|
+
'New Zealand v Pakistan'
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`batting_scorecard` and `bowling_scorecard` hold one list per innings and one dict per player. `over_by_over` gives runs and wickets for every over, and each `m.innings` entry has `fours` and `sixes`.
|
|
84
|
+
|
|
85
|
+
`m.ground` loads the ground record (`Ground` in `espncricinfo.grounds`): name, city, country, capacity.
|
|
74
86
|
|
|
75
87
|
## Players
|
|
76
88
|
|
|
@@ -100,6 +112,15 @@ The player ID is the number at the end of a player's profile URL.
|
|
|
100
112
|
'Chennai Super Kings'
|
|
101
113
|
```
|
|
102
114
|
|
|
115
|
+
Seasons that cross New Year, like the Big Bash League's, each have their own series ID. Look one up by the label ESPNcricinfo shows:
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
>>> bbl = Series(8044)
|
|
119
|
+
>>> season = bbl.season("2024/25") # also 2024, "2024-25" or "2024/2025"
|
|
120
|
+
>>> season.label, season.series_id
|
|
121
|
+
('2024/25', 1443056)
|
|
122
|
+
```
|
|
123
|
+
|
|
103
124
|
`series.season_objects` lists every season and `season.match_refs` that season's matches. `series.matches` collects MatchRefs across all seasons (1,254 for the IPL), and `series.current_matches` keeps those in progress. `team.players` loads the squad on demand. ESPN's records for some bilateral tours are incomplete, for example listing one team for a two-team series.
|
|
104
125
|
|
|
105
126
|
<!-- USAGE-END -->
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Grounds (ESPN "venues") from the ESPN core API."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
from espncricinfo._core import get_json
|
|
6
|
+
from espncricinfo.exceptions import NoGroundError
|
|
7
|
+
|
|
8
|
+
_VENUES = "http://core.espnuk.org/v2/sports/cricket/venues"
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Ground:
|
|
12
|
+
"""A cricket ground. Example values are for ``Ground(56293)``."""
|
|
13
|
+
|
|
14
|
+
#: ESPNcricinfo ground id, as in ``Match.ground_id``.
|
|
15
|
+
ground_id: int
|
|
16
|
+
#: ``'Adelaide Oval'``.
|
|
17
|
+
name: str
|
|
18
|
+
#: Short name, often the same as ``name``.
|
|
19
|
+
short_name: str | None
|
|
20
|
+
#: ``'Adelaide'``, or None.
|
|
21
|
+
city: str | None
|
|
22
|
+
#: ``'Australia'``, or None.
|
|
23
|
+
country: str | None
|
|
24
|
+
#: Seating capacity, or None if ESPN has none.
|
|
25
|
+
capacity: int | None
|
|
26
|
+
#: True for an indoor ground, or None if unknown.
|
|
27
|
+
indoor: bool | None
|
|
28
|
+
#: The core API venue record.
|
|
29
|
+
json: dict[str, Any]
|
|
30
|
+
|
|
31
|
+
def __init__(self, ground_id: int | str) -> None:
|
|
32
|
+
"""Load the ground record.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
ground_id: ESPNcricinfo ground id, e.g. ``Match.ground_id``.
|
|
36
|
+
"""
|
|
37
|
+
self.ground_id = int(ground_id)
|
|
38
|
+
self.json = get_json(f"{_VENUES}/{self.ground_id}", NoGroundError)
|
|
39
|
+
address = self.json.get("address") or {}
|
|
40
|
+
self.name = self.json["fullName"]
|
|
41
|
+
self.short_name = self.json.get("shortName")
|
|
42
|
+
self.city = address.get("city") or None
|
|
43
|
+
self.country = address.get("country") or None
|
|
44
|
+
self.capacity = self.json.get("capacity") or None
|
|
45
|
+
self.indoor = self.json.get("indoor")
|
|
46
|
+
|
|
47
|
+
def __str__(self) -> str:
|
|
48
|
+
"""Return the ground's name."""
|
|
49
|
+
return self.name
|
|
50
|
+
|
|
51
|
+
def __repr__(self) -> str:
|
|
52
|
+
"""Return ``Ground(ground_id)``."""
|
|
53
|
+
return f"Ground({self.ground_id})"
|
|
@@ -2,13 +2,19 @@
|
|
|
2
2
|
|
|
3
3
|
import asyncio
|
|
4
4
|
import json
|
|
5
|
+
import re
|
|
6
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
5
7
|
from datetime import date as _date
|
|
6
8
|
from datetime import datetime as _datetime
|
|
9
|
+
from functools import cached_property
|
|
7
10
|
from typing import Any, TypedDict
|
|
8
11
|
|
|
12
|
+
from bs4 import BeautifulSoup
|
|
9
13
|
from playwright.async_api import async_playwright
|
|
10
14
|
|
|
15
|
+
from espncricinfo import _core
|
|
11
16
|
from espncricinfo.exceptions import MatchNotFoundError, NoScorecardError
|
|
17
|
+
from espncricinfo.grounds import Ground
|
|
12
18
|
from espncricinfo.match_ref import MatchRef
|
|
13
19
|
|
|
14
20
|
|
|
@@ -50,9 +56,57 @@ async def _async_playwright_fetch(url):
|
|
|
50
56
|
return json.loads(m.group(1))
|
|
51
57
|
|
|
52
58
|
|
|
53
|
-
def _playwright_fetch(url):
|
|
54
|
-
"""Synchronous wrapper around _async_playwright_fetch.
|
|
55
|
-
|
|
59
|
+
def _playwright_fetch(url: str) -> dict[str, Any]:
|
|
60
|
+
"""Synchronous wrapper around _async_playwright_fetch.
|
|
61
|
+
|
|
62
|
+
Jupyter and other async callers already run an event loop on this thread,
|
|
63
|
+
and asyncio.run() refuses to nest inside one, so the fetch then runs on a
|
|
64
|
+
worker thread with its own loop.
|
|
65
|
+
"""
|
|
66
|
+
try:
|
|
67
|
+
asyncio.get_running_loop()
|
|
68
|
+
except RuntimeError:
|
|
69
|
+
return asyncio.run(_async_playwright_fetch(url))
|
|
70
|
+
with ThreadPoolExecutor(max_workers=1) as pool:
|
|
71
|
+
return pool.submit(lambda: asyncio.run(_async_playwright_fetch(url))).result()
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _boundary_count(inn: dict[str, Any], key: str) -> int | None:
|
|
75
|
+
"""Innings fours or sixes: ESPN's total, else the batters' sum, else None.
|
|
76
|
+
|
|
77
|
+
Where ESPN gives both, the total equals the batters' sum; older matches
|
|
78
|
+
often carry only the batters' figures, and the oldest carry neither.
|
|
79
|
+
"""
|
|
80
|
+
if inn.get(key) is not None:
|
|
81
|
+
return inn[key]
|
|
82
|
+
counts = [
|
|
83
|
+
bat.get(key)
|
|
84
|
+
for bat in inn.get("inningBatsmen") or []
|
|
85
|
+
if bat.get("battedType") == "yes"
|
|
86
|
+
]
|
|
87
|
+
if not counts or any(count is None for count in counts):
|
|
88
|
+
return None
|
|
89
|
+
return sum(counts)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _run_rate(inn: dict[str, Any]) -> float:
|
|
93
|
+
"""Runs per over for an innings; 0.0 before a ball is bowled.
|
|
94
|
+
|
|
95
|
+
ESPN writes overs in cricket notation, where 19.4 is 19 overs and 4 balls,
|
|
96
|
+
so dividing runs by it overstates the rate of an innings that ends
|
|
97
|
+
mid-over. Count balls instead: ESPN's ``balls``, else the overs figure
|
|
98
|
+
converted with ``ballsPerOver`` (6 unless ESPN says otherwise).
|
|
99
|
+
"""
|
|
100
|
+
try:
|
|
101
|
+
runs = inn.get("runs") or 0
|
|
102
|
+
per_over = inn.get("ballsPerOver") or 6
|
|
103
|
+
balls = inn.get("balls")
|
|
104
|
+
if not balls:
|
|
105
|
+
overs = float(inn.get("overs") or 0)
|
|
106
|
+
balls = int(overs) * per_over + round(overs % 1 * 10)
|
|
107
|
+
return round(runs * per_over / balls, 2) if balls > 0 else 0.0
|
|
108
|
+
except (TypeError, ValueError, ZeroDivisionError):
|
|
109
|
+
return 0.0
|
|
56
110
|
|
|
57
111
|
|
|
58
112
|
def _as_float(record: dict[str, Any] | None, key: str) -> float | None:
|
|
@@ -149,10 +203,7 @@ def _normalize(next_data, match_id, series_id):
|
|
|
149
203
|
for inn in innings_raw:
|
|
150
204
|
overs = inn.get("overs") or 0
|
|
151
205
|
runs = inn.get("runs") or 0
|
|
152
|
-
|
|
153
|
-
run_rate = round(runs / overs, 2) if overs > 0 else 0.0
|
|
154
|
-
except (ZeroDivisionError, TypeError):
|
|
155
|
-
run_rate = 0.0
|
|
206
|
+
run_rate = _run_rate(inn)
|
|
156
207
|
innings_normalized.append(
|
|
157
208
|
{
|
|
158
209
|
"batting_team_id": str(inn["team"]["objectId"]),
|
|
@@ -165,6 +216,9 @@ def _normalize(next_data, match_id, series_id):
|
|
|
165
216
|
"inningBatsmen": inn.get("inningBatsmen", []),
|
|
166
217
|
"inningBowlers": inn.get("inningBowlers", []),
|
|
167
218
|
"inningFallOfWickets": inn.get("inningFallOfWickets", []),
|
|
219
|
+
"inningOvers": inn.get("inningOvers") or [],
|
|
220
|
+
"fours": _boundary_count(inn, "fours"),
|
|
221
|
+
"sixes": _boundary_count(inn, "sixes"),
|
|
168
222
|
"extras": inn.get("extras"),
|
|
169
223
|
"byes": inn.get("byes"),
|
|
170
224
|
"legbyes": inn.get("legbyes"),
|
|
@@ -245,7 +299,9 @@ def _normalize(next_data, match_id, series_id):
|
|
|
245
299
|
"series": [
|
|
246
300
|
{
|
|
247
301
|
"series_name": series_data.get("name", ""),
|
|
248
|
-
"core_recreation_id": str(
|
|
302
|
+
"core_recreation_id": str(
|
|
303
|
+
series_data.get("objectId") or series_id or ""
|
|
304
|
+
),
|
|
249
305
|
"slug": series_data.get("slug", ""),
|
|
250
306
|
}
|
|
251
307
|
],
|
|
@@ -301,6 +357,16 @@ class BattingEntry(TypedDict):
|
|
|
301
357
|
batted: bool
|
|
302
358
|
|
|
303
359
|
|
|
360
|
+
class OverEntry(TypedDict):
|
|
361
|
+
"""One over of :attr:`Match.over_by_over`."""
|
|
362
|
+
|
|
363
|
+
over: int
|
|
364
|
+
runs: int
|
|
365
|
+
wickets: int
|
|
366
|
+
total_runs: int
|
|
367
|
+
total_wickets: int
|
|
368
|
+
|
|
369
|
+
|
|
304
370
|
class BowlingEntry(TypedDict):
|
|
305
371
|
"""One row of :attr:`Match.bowling_scorecard`."""
|
|
306
372
|
|
|
@@ -360,7 +426,8 @@ class Match:
|
|
|
360
426
|
scheduled_overs: int | None
|
|
361
427
|
#: Innings numbers as strings, ``['1', '2']``.
|
|
362
428
|
innings_list: list[str]
|
|
363
|
-
#: One dict per innings: team id, runs, wickets, overs
|
|
429
|
+
#: One dict per innings: team id, runs, wickets, overs, ``fours``, ``sixes``
|
|
430
|
+
#: (None where ESPN has no figures) and ESPN's raw lists.
|
|
364
431
|
innings: list[dict[str, Any]]
|
|
365
432
|
#: ESPN's raw innings records, including partnerships and commentary.
|
|
366
433
|
all_innings: list[dict[str, Any]]
|
|
@@ -413,21 +480,32 @@ class Match:
|
|
|
413
480
|
#: The parsed page, reshaped by ``_normalize``. Prefer the attributes.
|
|
414
481
|
json: dict[str, Any]
|
|
415
482
|
|
|
416
|
-
def __init__(self, match_id: int | str, series_id: int | str) -> None:
|
|
483
|
+
def __init__(self, match_id: int | str, series_id: int | str | None = None) -> None:
|
|
417
484
|
"""Fetch and parse the match.
|
|
418
485
|
|
|
419
486
|
Args:
|
|
420
487
|
match_id: ESPNcricinfo match (event) id.
|
|
421
|
-
series_id: ESPNcricinfo series
|
|
488
|
+
series_id: ESPNcricinfo series id the match belongs to. Optional:
|
|
489
|
+
without it the match page is found from the match id alone,
|
|
490
|
+
and ``series_id`` is read from the page.
|
|
491
|
+
|
|
492
|
+
Raises:
|
|
493
|
+
MatchNotFoundError: If ESPNcricinfo has no such match.
|
|
422
494
|
"""
|
|
423
495
|
self.match_id = int(match_id)
|
|
424
|
-
|
|
425
|
-
self.json = self._get_json()
|
|
496
|
+
given_series = int(series_id) if series_id is not None else None
|
|
497
|
+
self.json = self._get_json(given_series)
|
|
426
498
|
data = self.json
|
|
427
499
|
match = data["match"]
|
|
428
500
|
series = data["series"][-1]
|
|
429
501
|
|
|
430
|
-
|
|
502
|
+
page_series = series.get("core_recreation_id")
|
|
503
|
+
if page_series:
|
|
504
|
+
self.series_id = int(page_series)
|
|
505
|
+
elif given_series is not None:
|
|
506
|
+
self.series_id = given_series
|
|
507
|
+
else:
|
|
508
|
+
raise MatchNotFoundError(f"No series found for match {self.match_id}")
|
|
431
509
|
self.description = data["description"]
|
|
432
510
|
self.match_title = match["cms_match_title"]
|
|
433
511
|
self.match_class = (
|
|
@@ -495,13 +573,18 @@ class Match:
|
|
|
495
573
|
"""Return ``Match(match_id, series_id)``."""
|
|
496
574
|
return f"{self.__class__.__name__}({self.match_id!r}, {self.series_id!r})"
|
|
497
575
|
|
|
498
|
-
def _get_json(self) -> dict[str, Any]:
|
|
576
|
+
def _get_json(self, series_id: int | None) -> dict[str, Any]:
|
|
499
577
|
"""Fetch the match page and reshape its __NEXT_DATA__ blob."""
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
578
|
+
if series_id is None:
|
|
579
|
+
# ESPNcricinfo redirects its legacy match URL to the full match
|
|
580
|
+
# page, whatever series the match belongs to.
|
|
581
|
+
url = f"https://www.espncricinfo.com/matches/engine/match/{self.match_id}.html"
|
|
582
|
+
else:
|
|
583
|
+
url = (
|
|
584
|
+
f"https://www.espncricinfo.com/series/"
|
|
585
|
+
f"x-{series_id}/x-{self.match_id}/full-scorecard"
|
|
586
|
+
)
|
|
587
|
+
return _normalize(_playwright_fetch(url), self.match_id, series_id)
|
|
505
588
|
|
|
506
589
|
def _first_innings_of(self, team_id: str) -> dict[str, Any] | None:
|
|
507
590
|
return next(
|
|
@@ -642,6 +725,36 @@ class Match:
|
|
|
642
725
|
result.append([])
|
|
643
726
|
return result
|
|
644
727
|
|
|
728
|
+
@cached_property
|
|
729
|
+
def ground(self) -> Ground:
|
|
730
|
+
"""The match's ground, loaded on first access (one request)."""
|
|
731
|
+
return Ground(self.ground_id)
|
|
732
|
+
|
|
733
|
+
@property
|
|
734
|
+
def over_by_over(self) -> list[list[OverEntry]]:
|
|
735
|
+
"""Runs and wickets per over: one list per innings, one row per over.
|
|
736
|
+
|
|
737
|
+
Empty for an innings ESPN has no over data for, as with early Tests.
|
|
738
|
+
|
|
739
|
+
Example::
|
|
740
|
+
|
|
741
|
+
for over in m.over_by_over[0]:
|
|
742
|
+
print(over["over"], over["runs"], over["total_runs"])
|
|
743
|
+
"""
|
|
744
|
+
return [
|
|
745
|
+
[
|
|
746
|
+
OverEntry(
|
|
747
|
+
over=o["overNumber"],
|
|
748
|
+
runs=o["overRuns"],
|
|
749
|
+
wickets=o["overWickets"],
|
|
750
|
+
total_runs=o["totalRuns"],
|
|
751
|
+
total_wickets=o["totalWickets"],
|
|
752
|
+
)
|
|
753
|
+
for o in inn.get("inningOvers") or []
|
|
754
|
+
]
|
|
755
|
+
for inn in self.innings
|
|
756
|
+
]
|
|
757
|
+
|
|
645
758
|
# ------------------------------------------------------------------
|
|
646
759
|
# Static helpers
|
|
647
760
|
# ------------------------------------------------------------------
|
|
@@ -650,44 +763,98 @@ class Match:
|
|
|
650
763
|
def get_recent_matches(date: _date | str | None = None) -> list[MatchRef]:
|
|
651
764
|
"""Return MatchRefs for the matches on ESPNcricinfo's results page.
|
|
652
765
|
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
766
|
+
ESPN returns roughly the two weeks of matches ending on ``date``. Use
|
|
767
|
+
:meth:`get_matches_on` for the matches played on one day.
|
|
768
|
+
|
|
769
|
+
Args:
|
|
770
|
+
date: A ``datetime.date`` or a string in YYYY-MM-DD or DD-MM-YYYY
|
|
771
|
+
form; defaults to today.
|
|
657
772
|
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
form with an error page, so it is converted before the request.
|
|
773
|
+
Returns:
|
|
774
|
+
The listed matches, most recent first.
|
|
661
775
|
"""
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
776
|
+
return [ref for ref, _, _ in _results_page(_as_day(date))]
|
|
777
|
+
|
|
778
|
+
@staticmethod
|
|
779
|
+
def get_matches_on(date: _date | str | None = None) -> list[MatchRef]:
|
|
780
|
+
"""Return MatchRefs for the matches being played on one day.
|
|
781
|
+
|
|
782
|
+
A match counts if the day falls between its start and end dates, so a
|
|
783
|
+
Test appears on each of its days.
|
|
784
|
+
|
|
785
|
+
Args:
|
|
786
|
+
date: A ``datetime.date`` or a string in YYYY-MM-DD or DD-MM-YYYY
|
|
787
|
+
form; defaults to today.
|
|
788
|
+
|
|
789
|
+
Returns:
|
|
790
|
+
The matches on that day.
|
|
791
|
+
"""
|
|
792
|
+
day = _as_day(date)
|
|
793
|
+
return [ref for ref, start, end in _results_page(day) if start <= day <= end]
|
|
794
|
+
|
|
795
|
+
@staticmethod
|
|
796
|
+
def get_match_ids(year: int, match_format: int = 1) -> list[int]:
|
|
797
|
+
"""Return the ids of every international match of one format in a year.
|
|
798
|
+
|
|
799
|
+
Reads Statsguru's results table, so it covers matches back to 1877.
|
|
800
|
+
Pass each id to :class:`Match` to load it; each load starts a browser.
|
|
801
|
+
|
|
802
|
+
Args:
|
|
803
|
+
year: Calendar year, e.g. ``2023``.
|
|
804
|
+
match_format: Statsguru class: 1 Test, 2 ODI, 3 T20I,
|
|
805
|
+
8 women's Test, 9 women's ODI, 10 women's T20I.
|
|
806
|
+
|
|
807
|
+
Returns:
|
|
808
|
+
Match ids in the order Statsguru lists them (by date).
|
|
809
|
+
"""
|
|
810
|
+
response = _core.http_get(
|
|
811
|
+
"https://stats.espncricinfo.com/ci/engine/records/team/"
|
|
812
|
+
f"match_results.html?class={match_format};id={year};type=year"
|
|
675
813
|
)
|
|
814
|
+
response.raise_for_status()
|
|
815
|
+
soup = BeautifulSoup(response.text, "html.parser")
|
|
816
|
+
ids: list[int] = []
|
|
817
|
+
for row in soup.select("table.engineTable tr.data1"):
|
|
818
|
+
for link in row.find_all("a", href=True):
|
|
819
|
+
found = _MATCH_LINK.search(str(link["href"]))
|
|
820
|
+
if found and int(found.group(1)) not in ids:
|
|
821
|
+
ids.append(int(found.group(1)))
|
|
822
|
+
return ids
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
_MATCH_LINK = re.compile(r"/ci/engine/match/(\d+)\.html")
|
|
826
|
+
|
|
827
|
+
|
|
828
|
+
def _as_day(date: _date | str | None) -> _date:
|
|
829
|
+
"""Parse a date argument; ESPN's results page wants DD-MM-YYYY."""
|
|
830
|
+
if date is None:
|
|
831
|
+
return _datetime.now().astimezone().date()
|
|
832
|
+
if isinstance(date, _date):
|
|
833
|
+
return date
|
|
834
|
+
try:
|
|
835
|
+
return _date.fromisoformat(date)
|
|
836
|
+
except ValueError:
|
|
837
|
+
dd, mm, yyyy = (int(part) for part in date.split("-"))
|
|
838
|
+
return _date(yyyy, mm, dd)
|
|
676
839
|
|
|
677
|
-
|
|
840
|
+
|
|
841
|
+
def _results_page(day: _date) -> list[tuple[MatchRef, _date, _date]]:
|
|
842
|
+
"""(MatchRef, start date, end date) for each match on the results page."""
|
|
843
|
+
url = f"https://www.espncricinfo.com/live-cricket-match-results?date={day:%d-%m-%Y}"
|
|
844
|
+
next_data = _playwright_fetch(url)
|
|
845
|
+
try:
|
|
846
|
+
matches = next_data["props"]["appPageProps"]["data"]["data"]["content"][
|
|
847
|
+
"matches"
|
|
848
|
+
]
|
|
849
|
+
except (KeyError, TypeError):
|
|
850
|
+
return []
|
|
851
|
+
results = []
|
|
852
|
+
for m in matches:
|
|
678
853
|
try:
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
]
|
|
682
|
-
except (KeyError, TypeError):
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
for m in matches:
|
|
687
|
-
try:
|
|
688
|
-
series_id = m["series"]["objectId"]
|
|
689
|
-
match_id = m["objectId"]
|
|
690
|
-
results.append(MatchRef(series_id=series_id, match_id=match_id))
|
|
691
|
-
except (KeyError, TypeError):
|
|
692
|
-
continue
|
|
693
|
-
return results
|
|
854
|
+
ref = MatchRef(series_id=m["series"]["objectId"], match_id=m["objectId"])
|
|
855
|
+
start = _date.fromisoformat(m["startDate"][:10])
|
|
856
|
+
end = _date.fromisoformat((m.get("endDate") or m["startDate"])[:10])
|
|
857
|
+
except (KeyError, TypeError, ValueError):
|
|
858
|
+
continue
|
|
859
|
+
results.append((ref, start, end))
|
|
860
|
+
return results
|
|
@@ -24,8 +24,11 @@ class Season:
|
|
|
24
24
|
series_id: int
|
|
25
25
|
#: Core API URL of the season.
|
|
26
26
|
url: str
|
|
27
|
-
#: ``
|
|
27
|
+
#: ESPN's season year, the year the season starts: ``2024`` for 2024/25.
|
|
28
28
|
year: int
|
|
29
|
+
#: ESPNcricinfo's label: ``'2024/25'`` for a season that crosses New Year,
|
|
30
|
+
#: otherwise the year, e.g. ``'2025'``.
|
|
31
|
+
label: str
|
|
29
32
|
#: ``'Indian Premier League 2025'``.
|
|
30
33
|
name: str | None
|
|
31
34
|
#: Short name, or None.
|
|
@@ -56,6 +59,7 @@ class Season:
|
|
|
56
59
|
self.short_name = self.json.get("shortName")
|
|
57
60
|
self.start_date = _parse_date(self.json.get("startDate"))
|
|
58
61
|
self.end_date = _parse_date(self.json.get("endDate"))
|
|
62
|
+
self.label = _label(self.year, self.start_date, self.end_date)
|
|
59
63
|
|
|
60
64
|
@classmethod
|
|
61
65
|
def from_reference(cls, url: str) -> Season:
|
|
@@ -91,5 +95,11 @@ class Season:
|
|
|
91
95
|
return f"Season(id={self.id}, series_id={self.series_id}, name={self.name!r})"
|
|
92
96
|
|
|
93
97
|
|
|
98
|
+
def _label(year: int, start: datetime | None, end: datetime | None) -> str:
|
|
99
|
+
if start and end and end.year > start.year:
|
|
100
|
+
return f"{start.year}/{end.year % 100:02d}"
|
|
101
|
+
return str(year)
|
|
102
|
+
|
|
103
|
+
|
|
94
104
|
def _parse_date(value: str | None) -> datetime | None:
|
|
95
105
|
return datetime.fromisoformat(value) if value else None
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
"""Series (ESPN "league") records from the ESPN core API."""
|
|
2
2
|
|
|
3
|
+
import re
|
|
3
4
|
from functools import cached_property
|
|
4
5
|
from typing import Any
|
|
5
6
|
|
|
6
7
|
from espncricinfo import _core
|
|
7
8
|
from espncricinfo._core import collection_refs, get_json
|
|
8
|
-
from espncricinfo.exceptions import NoSeriesError
|
|
9
|
+
from espncricinfo.exceptions import NoSeasonError, NoSeriesError
|
|
9
10
|
from espncricinfo.match_ref import MatchRef
|
|
10
11
|
from espncricinfo.seasons import Season
|
|
11
12
|
|
|
12
13
|
_LEAGUES = "http://core.espnuk.org/v2/sports/cricket/leagues"
|
|
14
|
+
_SEASON_KEY = re.compile(r"(\d{4})(?:[/-](\d{2}|\d{4}))?")
|
|
13
15
|
|
|
14
16
|
|
|
15
17
|
class Series:
|
|
@@ -88,6 +90,39 @@ class Series:
|
|
|
88
90
|
"""Every season of the series, loaded on first access."""
|
|
89
91
|
return [Season.from_reference(url) for url in self.seasons]
|
|
90
92
|
|
|
93
|
+
def season(self, key: int | str) -> Season:
|
|
94
|
+
"""Return one season, by year or by ESPNcricinfo's two-year label.
|
|
95
|
+
|
|
96
|
+
Multi-year seasons live under their own series id, which this exposes
|
|
97
|
+
as ``season.series_id``: for the Big Bash League,
|
|
98
|
+
``Series(8044).season("2024/25").series_id`` is ``1443056``.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
key: ``2024``, ``"2024"``, ``"2024/25"``, ``"2024-25"`` or
|
|
102
|
+
``"2024/2025"``. A bare year matches the season starting then.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
The matching season.
|
|
106
|
+
|
|
107
|
+
Raises:
|
|
108
|
+
NoSeasonError: If the series has no such season.
|
|
109
|
+
"""
|
|
110
|
+
match = _SEASON_KEY.fullmatch(str(key).strip())
|
|
111
|
+
if match is None:
|
|
112
|
+
raise NoSeasonError(f"Not a season year or label: {key!r}")
|
|
113
|
+
start, end = match.groups()
|
|
114
|
+
ref = next(
|
|
115
|
+
(r for r in self.seasons if r.rstrip("/").endswith(f"/{start}")), None
|
|
116
|
+
)
|
|
117
|
+
if ref is None:
|
|
118
|
+
raise NoSeasonError(f"{self.name} has no season starting in {start}")
|
|
119
|
+
season = Season.from_reference(ref)
|
|
120
|
+
if end is not None and season.label != f"{start}/{end[-2:]}":
|
|
121
|
+
raise NoSeasonError(
|
|
122
|
+
f"{self.name} {start} season is labeled {season.label!r}, not {key!r}"
|
|
123
|
+
)
|
|
124
|
+
return season
|
|
125
|
+
|
|
91
126
|
@cached_property
|
|
92
127
|
def current_season(self) -> Season | None:
|
|
93
128
|
"""The season ESPN marks as current, or None."""
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["uv_build>=0.
|
|
2
|
+
requires = ["uv_build>=0.13.1,<0.14"]
|
|
3
3
|
build-backend = "uv_build"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "python-espncricinfo"
|
|
7
|
-
version = "1.0
|
|
7
|
+
version = "1.2.0"
|
|
8
8
|
description = "Python client for ESPNcricinfo match, series, season, team and player data"
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.
|
|
10
|
+
requires-python = ">=3.13"
|
|
11
11
|
license = "MIT"
|
|
12
12
|
license-files = ["LICENSE.txt"]
|
|
13
13
|
keywords = [
|
|
@@ -26,17 +26,16 @@ classifiers = [
|
|
|
26
26
|
"Operating System :: OS Independent",
|
|
27
27
|
"Programming Language :: Python :: 3",
|
|
28
28
|
"Programming Language :: Python :: 3 :: Only",
|
|
29
|
-
"Programming Language :: Python :: 3.12",
|
|
30
29
|
"Programming Language :: Python :: 3.13",
|
|
31
30
|
"Programming Language :: Python :: 3.14",
|
|
32
31
|
"Topic :: Internet :: WWW/HTTP",
|
|
33
32
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
34
33
|
]
|
|
35
34
|
dependencies = [
|
|
36
|
-
"requests",
|
|
37
|
-
"beautifulsoup4",
|
|
38
|
-
"dateparser",
|
|
39
|
-
"lxml",
|
|
35
|
+
"requests>=2.32.2",
|
|
36
|
+
"beautifulsoup4>=4.12.3",
|
|
37
|
+
"dateparser>=1.2.1",
|
|
38
|
+
"lxml>=5.3.0",
|
|
40
39
|
"playwright>=1.48.0",
|
|
41
40
|
]
|
|
42
41
|
|
|
@@ -46,7 +45,6 @@ email = "dwillis@gmail.com"
|
|
|
46
45
|
|
|
47
46
|
[[project.authors]]
|
|
48
47
|
name = "Gaurav Sood"
|
|
49
|
-
email = "gsood07@gmail.com"
|
|
50
48
|
|
|
51
49
|
[project.urls]
|
|
52
50
|
Homepage = "https://github.com/outside-edge/python-espncricinfo"
|
|
@@ -76,7 +74,7 @@ test = [
|
|
|
76
74
|
|
|
77
75
|
[tool.ruff]
|
|
78
76
|
line-length = 88
|
|
79
|
-
target-version = "
|
|
77
|
+
target-version = "py313"
|
|
80
78
|
|
|
81
79
|
[tool.ruff.lint]
|
|
82
80
|
external = ["DOC"]
|
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
[build-system]
|
|
2
|
-
requires = ["uv_build>=0.
|
|
2
|
+
requires = ["uv_build>=0.13.1,<0.14"]
|
|
3
3
|
build-backend = "uv_build"
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "python-espncricinfo"
|
|
7
|
-
version = "1.0
|
|
7
|
+
version = "1.2.0"
|
|
8
8
|
description = "Python client for ESPNcricinfo match, series, season, team and player data"
|
|
9
9
|
readme = "README.md"
|
|
10
|
-
requires-python = ">=3.
|
|
10
|
+
requires-python = ">=3.13"
|
|
11
11
|
license = "MIT"
|
|
12
12
|
license-files = ["LICENSE.txt"]
|
|
13
13
|
authors = [
|
|
14
14
|
{name = "Derek Willis", email = "dwillis@gmail.com"},
|
|
15
|
-
{name = "Gaurav Sood"
|
|
15
|
+
{name = "Gaurav Sood"},
|
|
16
16
|
]
|
|
17
17
|
keywords = ["espncricinfo", "cricket", "t20", "odi", "test cricket", "scorecard", "sports data"]
|
|
18
18
|
classifiers = [
|
|
@@ -22,13 +22,12 @@ classifiers = [
|
|
|
22
22
|
"Operating System :: OS Independent",
|
|
23
23
|
"Programming Language :: Python :: 3",
|
|
24
24
|
"Programming Language :: Python :: 3 :: Only",
|
|
25
|
-
"Programming Language :: Python :: 3.12",
|
|
26
25
|
"Programming Language :: Python :: 3.13",
|
|
27
26
|
"Programming Language :: Python :: 3.14",
|
|
28
27
|
"Topic :: Internet :: WWW/HTTP",
|
|
29
28
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
30
29
|
]
|
|
31
|
-
dependencies = ["requests", "beautifulsoup4", "dateparser", "lxml", "playwright>=1.48.0"]
|
|
30
|
+
dependencies = ["requests>=2.32.2", "beautifulsoup4>=4.12.3", "dateparser>=1.2.1", "lxml>=5.3.0", "playwright>=1.48.0"]
|
|
32
31
|
|
|
33
32
|
[project.urls]
|
|
34
33
|
Homepage = "https://github.com/outside-edge/python-espncricinfo"
|
|
@@ -44,7 +43,7 @@ test = ["pytest>=8", "pytest-cov>=6"]
|
|
|
44
43
|
|
|
45
44
|
[tool.ruff]
|
|
46
45
|
line-length = 88
|
|
47
|
-
target-version = "
|
|
46
|
+
target-version = "py313"
|
|
48
47
|
|
|
49
48
|
[tool.ruff.lint]
|
|
50
49
|
external = ["DOC"]
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|