python-espncricinfo 1.0.1__tar.gz → 1.1.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-espncricinfo
3
- Version: 1.0.1
3
+ Version: 1.1.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
@@ -45,7 +45,7 @@ A Python client for ESPNcricinfo match, series, season, team and player data.
45
45
 
46
46
  ## Description
47
47
 
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 both a `match_id` and a `series_id`, which `Match.get_recent_matches()` and `Series(...).matches` provide.
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 only a `match_id`; `Match.get_recent_matches()` and `Series(...).matches` list them.
49
49
 
50
50
  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
51
 
@@ -83,14 +83,14 @@ MatchRef(series_id=1523975, match_id=1523981)
83
83
  >>> series_id, match_id = refs[0] # MatchRefs unpack like tuples
84
84
  ```
85
85
 
86
- `Summary(date=...)` wraps the same call; its result is in `.matches`.
86
+ 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=...)` wraps the same call; its result is in `.matches`.
87
87
 
88
88
  ## A single match
89
89
 
90
- A match needs both its match ID and series ID: the two numbers in a match page URL, or a `MatchRef`. Loading a match starts a headless WebKit browser.
90
+ 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
91
 
92
92
  ```python
93
- >>> m = Match(1478914, 1478874) # same as MatchRef(1478874, 1478914).to_match()
93
+ >>> m = Match(1478914)
94
94
  >>> m.description
95
95
  'IND Women v AUS Women'
96
96
  >>> m.match_class
@@ -103,7 +103,19 @@ A match needs both its match ID and series ID: the two numbers in a match page U
103
103
  ('D Brown', 0)
104
104
  ```
105
105
 
106
- `batting_scorecard` and `bowling_scorecard` hold one list per innings and one dict per player.
106
+ 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:
107
+
108
+ ```python
109
+ >>> ids = Match.get_match_ids(2023, 1)
110
+ >>> len(ids)
111
+ 34
112
+ >>> Match(ids[0]).description
113
+ 'New Zealand v Pakistan'
114
+ ```
115
+
116
+ `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`.
117
+
118
+ `m.ground` loads the ground record (`Ground` in `espncricinfo.grounds`): name, city, country, capacity.
107
119
 
108
120
  ## Players
109
121
 
@@ -133,6 +145,15 @@ The player ID is the number at the end of a player's profile URL.
133
145
  'Chennai Super Kings'
134
146
  ```
135
147
 
148
+ 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:
149
+
150
+ ```python
151
+ >>> bbl = Series(8044)
152
+ >>> season = bbl.season("2024/25") # also 2024, "2024-25" or "2024/2025"
153
+ >>> season.label, season.series_id
154
+ ('2024/25', 1443056)
155
+ ```
156
+
136
157
  `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
158
 
138
159
  <!-- 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 both a `match_id` and a `series_id`, which `Match.get_recent_matches()` and `Series(...).matches` provide.
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=...)` wraps the same call; its result is in `.matches`.
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=...)` wraps the same call; its result is in `.matches`.
54
54
 
55
55
  ## A single match
56
56
 
57
- A match needs both its match ID and series ID: the two numbers in a match page URL, or a `MatchRef`. Loading a match starts a headless WebKit browser.
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, 1478874) # same as MatchRef(1478874, 1478914).to_match()
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
- `batting_scorecard` and `bowling_scorecard` hold one list per innings and one dict per player.
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 -->
@@ -23,3 +23,7 @@ class NoSeasonError(TypeError):
23
23
 
24
24
  class NoTeamError(TypeError):
25
25
  """Exception raised if a team does not exist in a series."""
26
+
27
+
28
+ class NoGroundError(TypeError):
29
+ """Raised when a ground does not exist."""
@@ -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,37 @@ 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
- return asyncio.run(_async_playwright_fetch(url))
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)
56
90
 
57
91
 
58
92
  def _as_float(record: dict[str, Any] | None, key: str) -> float | None:
@@ -165,6 +199,9 @@ def _normalize(next_data, match_id, series_id):
165
199
  "inningBatsmen": inn.get("inningBatsmen", []),
166
200
  "inningBowlers": inn.get("inningBowlers", []),
167
201
  "inningFallOfWickets": inn.get("inningFallOfWickets", []),
202
+ "inningOvers": inn.get("inningOvers") or [],
203
+ "fours": _boundary_count(inn, "fours"),
204
+ "sixes": _boundary_count(inn, "sixes"),
168
205
  "extras": inn.get("extras"),
169
206
  "byes": inn.get("byes"),
170
207
  "legbyes": inn.get("legbyes"),
@@ -245,7 +282,9 @@ def _normalize(next_data, match_id, series_id):
245
282
  "series": [
246
283
  {
247
284
  "series_name": series_data.get("name", ""),
248
- "core_recreation_id": str(series_data.get("objectId", series_id)),
285
+ "core_recreation_id": str(
286
+ series_data.get("objectId") or series_id or ""
287
+ ),
249
288
  "slug": series_data.get("slug", ""),
250
289
  }
251
290
  ],
@@ -301,6 +340,16 @@ class BattingEntry(TypedDict):
301
340
  batted: bool
302
341
 
303
342
 
343
+ class OverEntry(TypedDict):
344
+ """One over of :attr:`Match.over_by_over`."""
345
+
346
+ over: int
347
+ runs: int
348
+ wickets: int
349
+ total_runs: int
350
+ total_wickets: int
351
+
352
+
304
353
  class BowlingEntry(TypedDict):
305
354
  """One row of :attr:`Match.bowling_scorecard`."""
306
355
 
@@ -360,7 +409,8 @@ class Match:
360
409
  scheduled_overs: int | None
361
410
  #: Innings numbers as strings, ``['1', '2']``.
362
411
  innings_list: list[str]
363
- #: One dict per innings: team id, runs, wickets, overs and ESPN's raw lists.
412
+ #: One dict per innings: team id, runs, wickets, overs, ``fours``, ``sixes``
413
+ #: (None where ESPN has no figures) and ESPN's raw lists.
364
414
  innings: list[dict[str, Any]]
365
415
  #: ESPN's raw innings records, including partnerships and commentary.
366
416
  all_innings: list[dict[str, Any]]
@@ -413,21 +463,32 @@ class Match:
413
463
  #: The parsed page, reshaped by ``_normalize``. Prefer the attributes.
414
464
  json: dict[str, Any]
415
465
 
416
- def __init__(self, match_id: int | str, series_id: int | str) -> None:
466
+ def __init__(self, match_id: int | str, series_id: int | str | None = None) -> None:
417
467
  """Fetch and parse the match.
418
468
 
419
469
  Args:
420
470
  match_id: ESPNcricinfo match (event) id.
421
- series_id: ESPNcricinfo series (league) id the match belongs to.
471
+ series_id: ESPNcricinfo series id the match belongs to. Optional:
472
+ without it the match page is found from the match id alone,
473
+ and ``series_id`` is read from the page.
474
+
475
+ Raises:
476
+ MatchNotFoundError: If ESPNcricinfo has no such match.
422
477
  """
423
478
  self.match_id = int(match_id)
424
- self.series_id = int(series_id)
425
- self.json = self._get_json()
479
+ given_series = int(series_id) if series_id is not None else None
480
+ self.json = self._get_json(given_series)
426
481
  data = self.json
427
482
  match = data["match"]
428
483
  series = data["series"][-1]
429
484
 
430
- self.series_id = int(series["core_recreation_id"])
485
+ page_series = series.get("core_recreation_id")
486
+ if page_series:
487
+ self.series_id = int(page_series)
488
+ elif given_series is not None:
489
+ self.series_id = given_series
490
+ else:
491
+ raise MatchNotFoundError(f"No series found for match {self.match_id}")
431
492
  self.description = data["description"]
432
493
  self.match_title = match["cms_match_title"]
433
494
  self.match_class = (
@@ -495,13 +556,18 @@ class Match:
495
556
  """Return ``Match(match_id, series_id)``."""
496
557
  return f"{self.__class__.__name__}({self.match_id!r}, {self.series_id!r})"
497
558
 
498
- def _get_json(self) -> dict[str, Any]:
559
+ def _get_json(self, series_id: int | None) -> dict[str, Any]:
499
560
  """Fetch the match page and reshape its __NEXT_DATA__ blob."""
500
- url = (
501
- f"https://www.espncricinfo.com/series/"
502
- f"x-{self.series_id}/x-{self.match_id}/full-scorecard"
503
- )
504
- return _normalize(_playwright_fetch(url), self.match_id, self.series_id)
561
+ if series_id is None:
562
+ # ESPNcricinfo redirects its legacy match URL to the full match
563
+ # page, whatever series the match belongs to.
564
+ url = f"https://www.espncricinfo.com/matches/engine/match/{self.match_id}.html"
565
+ else:
566
+ url = (
567
+ f"https://www.espncricinfo.com/series/"
568
+ f"x-{series_id}/x-{self.match_id}/full-scorecard"
569
+ )
570
+ return _normalize(_playwright_fetch(url), self.match_id, series_id)
505
571
 
506
572
  def _first_innings_of(self, team_id: str) -> dict[str, Any] | None:
507
573
  return next(
@@ -642,6 +708,36 @@ class Match:
642
708
  result.append([])
643
709
  return result
644
710
 
711
+ @cached_property
712
+ def ground(self) -> Ground:
713
+ """The match's ground, loaded on first access (one request)."""
714
+ return Ground(self.ground_id)
715
+
716
+ @property
717
+ def over_by_over(self) -> list[list[OverEntry]]:
718
+ """Runs and wickets per over: one list per innings, one row per over.
719
+
720
+ Empty for an innings ESPN has no over data for, as with early Tests.
721
+
722
+ Example::
723
+
724
+ for over in m.over_by_over[0]:
725
+ print(over["over"], over["runs"], over["total_runs"])
726
+ """
727
+ return [
728
+ [
729
+ OverEntry(
730
+ over=o["overNumber"],
731
+ runs=o["overRuns"],
732
+ wickets=o["overWickets"],
733
+ total_runs=o["totalRuns"],
734
+ total_wickets=o["totalWickets"],
735
+ )
736
+ for o in inn.get("inningOvers") or []
737
+ ]
738
+ for inn in self.innings
739
+ ]
740
+
645
741
  # ------------------------------------------------------------------
646
742
  # Static helpers
647
743
  # ------------------------------------------------------------------
@@ -650,44 +746,98 @@ class Match:
650
746
  def get_recent_matches(date: _date | str | None = None) -> list[MatchRef]:
651
747
  """Return MatchRefs for the matches on ESPNcricinfo's results page.
652
748
 
653
- Fetches https://www.espncricinfo.com/live-cricket-match-results
654
- (with ?date=DD-MM-YYYY) and extracts match data from
655
- __NEXT_DATA__ at props.appPageProps.data.data.content.matches.
656
- ESPN returns roughly the two weeks of matches ending on that date.
749
+ ESPN returns roughly the two weeks of matches ending on ``date``. Use
750
+ :meth:`get_matches_on` for the matches played on one day.
751
+
752
+ Args:
753
+ date: A ``datetime.date`` or a string in YYYY-MM-DD or DD-MM-YYYY
754
+ form; defaults to today.
657
755
 
658
- ``date`` may be a ``datetime.date`` or a string in YYYY-MM-DD or
659
- DD-MM-YYYY form; it defaults to today. ESPN answers the YYYY-MM-DD
660
- form with an error page, so it is converted before the request.
756
+ Returns:
757
+ The listed matches, most recent first.
661
758
  """
662
- if date is None:
663
- day = _datetime.now().astimezone().date()
664
- elif isinstance(date, _date):
665
- day = date
666
- else:
667
- try:
668
- day = _date.fromisoformat(date)
669
- except ValueError:
670
- dd, mm, yyyy = (int(part) for part in date.split("-"))
671
- day = _date(yyyy, mm, dd)
672
- url = (
673
- "https://www.espncricinfo.com/live-cricket-match-results"
674
- f"?date={day:%d-%m-%Y}"
759
+ return [ref for ref, _, _ in _results_page(_as_day(date))]
760
+
761
+ @staticmethod
762
+ def get_matches_on(date: _date | str | None = None) -> list[MatchRef]:
763
+ """Return MatchRefs for the matches being played on one day.
764
+
765
+ A match counts if the day falls between its start and end dates, so a
766
+ Test appears on each of its days.
767
+
768
+ Args:
769
+ date: A ``datetime.date`` or a string in YYYY-MM-DD or DD-MM-YYYY
770
+ form; defaults to today.
771
+
772
+ Returns:
773
+ The matches on that day.
774
+ """
775
+ day = _as_day(date)
776
+ return [ref for ref, start, end in _results_page(day) if start <= day <= end]
777
+
778
+ @staticmethod
779
+ def get_match_ids(year: int, match_format: int = 1) -> list[int]:
780
+ """Return the ids of every international match of one format in a year.
781
+
782
+ Reads Statsguru's results table, so it covers matches back to 1877.
783
+ Pass each id to :class:`Match` to load it; each load starts a browser.
784
+
785
+ Args:
786
+ year: Calendar year, e.g. ``2023``.
787
+ match_format: Statsguru class: 1 Test, 2 ODI, 3 T20I,
788
+ 8 women's Test, 9 women's ODI, 10 women's T20I.
789
+
790
+ Returns:
791
+ Match ids in the order Statsguru lists them (by date).
792
+ """
793
+ response = _core.http_get(
794
+ "https://stats.espncricinfo.com/ci/engine/records/team/"
795
+ f"match_results.html?class={match_format};id={year};type=year"
675
796
  )
797
+ response.raise_for_status()
798
+ soup = BeautifulSoup(response.text, "html.parser")
799
+ ids: list[int] = []
800
+ for row in soup.select("table.engineTable tr.data1"):
801
+ for link in row.find_all("a", href=True):
802
+ found = _MATCH_LINK.search(str(link["href"]))
803
+ if found and int(found.group(1)) not in ids:
804
+ ids.append(int(found.group(1)))
805
+ return ids
806
+
807
+
808
+ _MATCH_LINK = re.compile(r"/ci/engine/match/(\d+)\.html")
809
+
810
+
811
+ def _as_day(date: _date | str | None) -> _date:
812
+ """Parse a date argument; ESPN's results page wants DD-MM-YYYY."""
813
+ if date is None:
814
+ return _datetime.now().astimezone().date()
815
+ if isinstance(date, _date):
816
+ return date
817
+ try:
818
+ return _date.fromisoformat(date)
819
+ except ValueError:
820
+ dd, mm, yyyy = (int(part) for part in date.split("-"))
821
+ return _date(yyyy, mm, dd)
822
+
676
823
 
677
- next_data = _playwright_fetch(url)
824
+ def _results_page(day: _date) -> list[tuple[MatchRef, _date, _date]]:
825
+ """(MatchRef, start date, end date) for each match on the results page."""
826
+ url = f"https://www.espncricinfo.com/live-cricket-match-results?date={day:%d-%m-%Y}"
827
+ next_data = _playwright_fetch(url)
828
+ try:
829
+ matches = next_data["props"]["appPageProps"]["data"]["data"]["content"][
830
+ "matches"
831
+ ]
832
+ except (KeyError, TypeError):
833
+ return []
834
+ results = []
835
+ for m in matches:
678
836
  try:
679
- matches = next_data["props"]["appPageProps"]["data"]["data"]["content"][
680
- "matches"
681
- ]
682
- except (KeyError, TypeError):
683
- return []
684
-
685
- results = []
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
837
+ ref = MatchRef(series_id=m["series"]["objectId"], match_id=m["objectId"])
838
+ start = _date.fromisoformat(m["startDate"][:10])
839
+ end = _date.fromisoformat((m.get("endDate") or m["startDate"])[:10])
840
+ except (KeyError, TypeError, ValueError):
841
+ continue
842
+ results.append((ref, start, end))
843
+ 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
- #: ``2025``.
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,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["uv_build>=0.12.5,<0.14"]
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.1"
7
+ version = "1.1.0"
8
8
  description = "Python client for ESPNcricinfo match, series, season, team and player data"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["uv_build>=0.12.5,<0.14"]
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.1"
7
+ version = "1.1.0"
8
8
  description = "Python client for ESPNcricinfo match, series, season, team and player data"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"