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/match.py ADDED
@@ -0,0 +1,693 @@
1
+ """Match data scraped from ESPNcricinfo match pages via Playwright."""
2
+
3
+ import asyncio
4
+ import json
5
+ from datetime import date as _date
6
+ from datetime import datetime as _datetime
7
+ from typing import Any, TypedDict
8
+
9
+ from playwright.async_api import async_playwright
10
+
11
+ from espncricinfo.exceptions import MatchNotFoundError, NoScorecardError
12
+ from espncricinfo.match_ref import MatchRef
13
+
14
+
15
+ async def _async_playwright_fetch(url):
16
+ """Fetch a page via Playwright (WebKit) and return the parsed __NEXT_DATA__ dict.
17
+
18
+ WebKit is used because Akamai does not block it in headless mode.
19
+ Raises MatchNotFoundError on 404.
20
+ """
21
+ async with async_playwright() as pw:
22
+ browser = await pw.webkit.launch(headless=True)
23
+ context = await browser.new_context(
24
+ user_agent=(
25
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
26
+ "AppleWebKit/605.1.15 (KHTML, like Gecko) "
27
+ "Version/16.0 Safari/605.1.15"
28
+ ),
29
+ )
30
+ page = await context.new_page()
31
+
32
+ response = await page.goto(url, wait_until="domcontentloaded", timeout=60000)
33
+ if response and response.status == 404:
34
+ await browser.close()
35
+ raise MatchNotFoundError(f"Match not found at {url}")
36
+
37
+ content = await page.content()
38
+ await browser.close()
39
+
40
+ # Extract __NEXT_DATA__ from the HTML
41
+ import re
42
+
43
+ m = re.search(
44
+ r'<script id="__NEXT_DATA__" type="application/json">(.*?)</script>',
45
+ content,
46
+ re.DOTALL,
47
+ )
48
+ if not m:
49
+ raise NoScorecardError("Could not find __NEXT_DATA__ in page")
50
+ return json.loads(m.group(1))
51
+
52
+
53
+ def _playwright_fetch(url):
54
+ """Synchronous wrapper around _async_playwright_fetch."""
55
+ return asyncio.run(_async_playwright_fetch(url))
56
+
57
+
58
+ def _as_float(record: dict[str, Any] | None, key: str) -> float | None:
59
+ """Return ``record[key]`` as a float, or None if absent or not numeric."""
60
+ if record is None:
61
+ return None
62
+ try:
63
+ return float(record[key])
64
+ except (KeyError, TypeError, ValueError):
65
+ return None
66
+
67
+
68
+ def _normalize(next_data, match_id, series_id):
69
+ """Reshape a match page's __NEXT_DATA__ into the old engine JSON layout.
70
+
71
+ Match reads its attributes from this layout. Raw page data is kept under
72
+ ``_match``, ``_content`` and ``_match_players``.
73
+ """
74
+ try:
75
+ app_data = next_data["props"]["appPageProps"]["data"]
76
+ # Live pages return match/content directly; fixtures add a "data" level.
77
+ if "match" in app_data and "content" in app_data:
78
+ data = app_data
79
+ elif "data" in app_data:
80
+ data = app_data["data"]
81
+ else:
82
+ raise KeyError("no match/content in appPageProps.data")
83
+ except KeyError as exc:
84
+ raise NoScorecardError(f"Unexpected __NEXT_DATA__ structure: {exc}") from exc
85
+
86
+ match = data["match"]
87
+ content = data.get("content", {})
88
+ innings_raw = content.get("innings", [])
89
+ match_players = content.get("matchPlayers", {})
90
+ team_players_list = match_players.get("teamPlayers", [])
91
+
92
+ # ---- teams ----
93
+ teams_raw = match.get("teams", [])
94
+
95
+ # Build a lookup: team internal id -> objectId (for tossWinnerTeamId mapping)
96
+ team_id_to_objectid = {}
97
+ for t in teams_raw:
98
+ team_id_to_objectid[t["team"]["id"]] = str(t["team"]["objectId"])
99
+
100
+ # Build player lists per team (keyed by team objectId)
101
+ players_by_team = {}
102
+ for tp in team_players_list:
103
+ oid = str(tp["team"]["objectId"])
104
+ players_by_team[oid] = tp.get("players", [])
105
+
106
+ def build_team(t):
107
+ oid = str(t["team"]["objectId"])
108
+ return {
109
+ "team_id": oid,
110
+ "team_abbreviation": t["team"]["abbreviation"],
111
+ "team_name": t["team"]["name"],
112
+ "team_long_name": t["team"]["longName"],
113
+ "player": players_by_team.get(oid, []),
114
+ }
115
+
116
+ teams_normalized = [build_team(t) for t in teams_raw]
117
+
118
+ # ---- home_team_id ----
119
+ home_team_id = None
120
+ for t in teams_raw:
121
+ if t.get("isHome"):
122
+ home_team_id = str(t["team"]["objectId"])
123
+ break
124
+
125
+ # ---- toss ----
126
+ toss_winner_internal = match.get("tossWinnerTeamId")
127
+ toss_winner_team_id = (
128
+ team_id_to_objectid.get(toss_winner_internal, "")
129
+ if toss_winner_internal
130
+ else ""
131
+ )
132
+ toss_choice = match.get("tossWinnerChoice")
133
+ toss_decision = "1" if toss_choice == 1 else "2"
134
+ toss_decision_name = "bat" if toss_choice == 1 else "bowl"
135
+
136
+ # ---- winner ----
137
+ winner_internal = match.get("winnerTeamId")
138
+ winner_team_id = (
139
+ team_id_to_objectid.get(winner_internal, "") if winner_internal else ""
140
+ )
141
+
142
+ # ---- batting first ----
143
+ batting_first_team_id = ""
144
+ if innings_raw:
145
+ batting_first_team_id = str(innings_raw[0]["team"]["objectId"])
146
+
147
+ # ---- innings ----
148
+ innings_normalized = []
149
+ for inn in innings_raw:
150
+ overs = inn.get("overs") or 0
151
+ runs = inn.get("runs") or 0
152
+ try:
153
+ run_rate = round(runs / overs, 2) if overs > 0 else 0.0
154
+ except (ZeroDivisionError, TypeError):
155
+ run_rate = 0.0
156
+ innings_normalized.append(
157
+ {
158
+ "batting_team_id": str(inn["team"]["objectId"]),
159
+ "runs": runs,
160
+ "wickets": inn.get("wickets"),
161
+ "overs": str(overs),
162
+ "run_rate": str(run_rate),
163
+ "event_name": inn.get("event"),
164
+ "inning_number": inn.get("inningNumber"),
165
+ "inningBatsmen": inn.get("inningBatsmen", []),
166
+ "inningBowlers": inn.get("inningBowlers", []),
167
+ "inningFallOfWickets": inn.get("inningFallOfWickets", []),
168
+ "extras": inn.get("extras"),
169
+ "byes": inn.get("byes"),
170
+ "legbyes": inn.get("legbyes"),
171
+ "wides": inn.get("wides"),
172
+ "noballs": inn.get("noballs"),
173
+ "target": inn.get("target"),
174
+ }
175
+ )
176
+
177
+ # ---- ground location ----
178
+ ground = match.get("ground", {})
179
+ ground_location = ground.get("location", "") or ""
180
+ town = ground.get("town", {}) or {}
181
+ continent = None # not available in new API
182
+ city = town.get("name") or ground_location or None
183
+
184
+ # ---- series ----
185
+ series_data = match.get("series", {})
186
+
187
+ # ---- match class ----
188
+ intl_class_map = {
189
+ 1: "Test",
190
+ 2: "ODI",
191
+ 3: "T20I",
192
+ 10: "WT20I",
193
+ 11: "WODI",
194
+ 12: "WTest",
195
+ }
196
+ intl_class_id = match.get("internationalClassId")
197
+ intl_class_card = intl_class_map.get(intl_class_id, "") if intl_class_id else ""
198
+ general_class_card = match.get("format", "")
199
+
200
+ # ---- innings_list for centre ----
201
+ innings_list = [str(i + 1) for i in range(len(innings_normalized))]
202
+
203
+ # ---- description ----
204
+ if teams_raw and len(teams_raw) >= 2:
205
+ description = f"{teams_raw[0]['team']['name']} v {teams_raw[1]['team']['name']}"
206
+ else:
207
+ description = match.get("title", "")
208
+
209
+ return {
210
+ "description": description,
211
+ "match": {
212
+ "match_status": match.get("status", "").lower(),
213
+ "international_class_card": intl_class_card,
214
+ "general_class_card": general_class_card,
215
+ "season": match.get("season", ""),
216
+ "start_date_raw": (match.get("startDate") or "")[:10],
217
+ "cancelled_match": "Y" if match.get("isCancelled") else "N",
218
+ "ground_id": str(ground.get("objectId", "")),
219
+ "ground_name": ground.get("longName", ""),
220
+ "scheduled_overs": match.get("scheduledOvers"),
221
+ "home_team_id": home_team_id,
222
+ "winner_team_id": winner_team_id,
223
+ "toss_winner_team_id": toss_winner_team_id,
224
+ "toss_choice_team_id": toss_winner_team_id, # same in new API
225
+ "toss_decision": toss_decision,
226
+ "toss_decision_name": toss_decision_name,
227
+ "batting_first_team_id": batting_first_team_id,
228
+ "continent_name": continent,
229
+ "town_name": city,
230
+ "town_area": city,
231
+ "town_id": str(ground.get("objectId", "")),
232
+ "floodlit_name": match.get("floodlit", ""),
233
+ "legacy_url": f"/ci/engine/match/{match_id}.html",
234
+ "cms_match_title": match.get("title", ""),
235
+ "present_datetime_local": match.get("startDate", ""),
236
+ "present_datetime_gmt": match.get("startDate", ""),
237
+ "start_datetime_local": match.get("startDate", ""),
238
+ "start_datetime_gmt": match.get("startDate", ""),
239
+ "rain_rule": None,
240
+ "rain_rule_name": None,
241
+ "weather_location_code": None,
242
+ "followon": None,
243
+ "current_summary": match.get("statusText", ""),
244
+ },
245
+ "series": [
246
+ {
247
+ "series_name": series_data.get("name", ""),
248
+ "core_recreation_id": str(series_data.get("objectId", series_id)),
249
+ "slug": series_data.get("slug", ""),
250
+ }
251
+ ],
252
+ "live": {
253
+ "status": match.get("statusText", ""),
254
+ },
255
+ "team": teams_normalized,
256
+ "innings": innings_normalized,
257
+ "official": [],
258
+ "centre": {
259
+ "common": {
260
+ "innings_list": innings_list,
261
+ "batting": [],
262
+ "bowling": [],
263
+ "innings": None,
264
+ },
265
+ "fow": None,
266
+ },
267
+ # Keep raw new-API data accessible
268
+ "_match": match,
269
+ "_content": content,
270
+ "_match_players": match_players,
271
+ }
272
+
273
+
274
+ class MatchTeam(TypedDict):
275
+ """One side of a match, as held in :attr:`Match.team_1` and ``team_2``."""
276
+
277
+ team_id: str
278
+ team_abbreviation: str
279
+ team_name: str
280
+ team_long_name: str
281
+ player: list[dict[str, Any]]
282
+
283
+
284
+ class BattingEntry(TypedDict):
285
+ """One row of :attr:`Match.batting_scorecard`.
286
+
287
+ Numeric fields are ``None`` for players who did not bat.
288
+ """
289
+
290
+ name: str | None
291
+ full_name: str | None
292
+ player_id: int | None
293
+ runs: int | None
294
+ balls: int | None
295
+ minutes: int | None
296
+ fours: int | None
297
+ sixes: int | None
298
+ strike_rate: float | None
299
+ is_out: bool
300
+ dismissal: str
301
+ batted: bool
302
+
303
+
304
+ class BowlingEntry(TypedDict):
305
+ """One row of :attr:`Match.bowling_scorecard`."""
306
+
307
+ name: str | None
308
+ full_name: str | None
309
+ player_id: int | None
310
+ overs: float | None
311
+ maidens: int | None
312
+ runs: int | None
313
+ wickets: int | None
314
+ economy: float | None
315
+ wides: int | None
316
+ no_balls: int | None
317
+ dots: int | None
318
+
319
+
320
+ class Match:
321
+ """One match, loaded from its ESPNcricinfo full-scorecard page.
322
+
323
+ Loading starts a headless WebKit browser, because the site's CDN refuses
324
+ plain HTTP clients. Example values below are for ``Match(1478914, 1478874)``.
325
+ """
326
+
327
+ #: ESPNcricinfo match id.
328
+ match_id: int
329
+ #: ESPNcricinfo series id, as ESPN reports it for this match.
330
+ series_id: int
331
+ #: ``'IND Women v AUS Women'``.
332
+ description: str
333
+ #: Match title within the series, e.g. ``'3rd T20I'``.
334
+ match_title: str
335
+ #: Format, e.g. ``'WT20I'``, ``'T20'``, ``'Test'``.
336
+ match_class: str
337
+ #: ESPN status, e.g. ``'result'``; ``'dormant'`` for unplayed matches.
338
+ status: str
339
+ #: Result line, e.g. ``'IND Women won by 17 runs'``.
340
+ result: str
341
+ #: Season label, e.g. ``'2025/26'``.
342
+ season: str
343
+ #: ``'India Women in Australia'``.
344
+ series_name: str | None
345
+ #: Start date, ``'YYYY-MM-DD'``.
346
+ date: str
347
+ #: Start time in UTC, ISO 8601.
348
+ start_datetime: str
349
+ #: True if ESPN marks the match as canceled.
350
+ canceled: bool
351
+ #: ESPN ground id.
352
+ ground_id: str
353
+ #: ``'Adelaide Oval'``.
354
+ ground_name: str
355
+ #: Town or city of the ground.
356
+ town_name: str | None
357
+ #: Floodlight setting, e.g. ``'night'``.
358
+ lighting: str
359
+ #: Scheduled overs per side; None for Tests.
360
+ scheduled_overs: int | None
361
+ #: Innings numbers as strings, ``['1', '2']``.
362
+ innings_list: list[str]
363
+ #: One dict per innings: team id, runs, wickets, overs and ESPN's raw lists.
364
+ innings: list[dict[str, Any]]
365
+ #: ESPN's raw innings records, including partnerships and commentary.
366
+ all_innings: list[dict[str, Any]]
367
+ #: ESPN's raw squads (``teamPlayers``), or None.
368
+ rosters: dict[str, Any] | None
369
+ #: First-listed side.
370
+ team_1: MatchTeam
371
+ #: Second-listed side.
372
+ team_2: MatchTeam
373
+ #: ``team_1['team_id']``.
374
+ team_1_id: str
375
+ #: ``team_2['team_id']``.
376
+ team_2_id: str
377
+ #: ``team_1['team_abbreviation']``, e.g. ``'IND-W'``.
378
+ team_1_abbreviation: str
379
+ #: ``team_2['team_abbreviation']``.
380
+ team_2_abbreviation: str
381
+ #: ESPN's raw player records for team 1.
382
+ team_1_players: list[dict[str, Any]]
383
+ #: ESPN's raw player records for team 2.
384
+ team_2_players: list[dict[str, Any]]
385
+ #: Team 1's first innings record, or None if it has not batted.
386
+ team_1_innings: dict[str, Any] | None
387
+ #: Team 2's first innings record, or None if it has not batted.
388
+ team_2_innings: dict[str, Any] | None
389
+ #: Team 1's runs per over, or None.
390
+ team_1_run_rate: float | None
391
+ #: Team 2's runs per over, or None.
392
+ team_2_run_rate: float | None
393
+ #: Overs team 1 batted, or None.
394
+ team_1_overs_batted: float | None
395
+ #: Overs team 2 batted, or None.
396
+ team_2_overs_batted: float | None
397
+ #: Abbreviation of the home side, or None.
398
+ home_team: str | None
399
+ #: Abbreviation of the side that batted first, or None.
400
+ batting_first: str | None
401
+ #: Abbreviation of the winner; None for no result, a tie or an unplayed match.
402
+ match_winner: str | None
403
+ #: Team id of the toss winner, or None.
404
+ toss_winner: str | None
405
+ #: ``'bat'`` or ``'bowl'``, or None before the toss.
406
+ toss_decision_name: str | None
407
+ #: Core API event URL.
408
+ event_url: str
409
+ #: Core API URL for the ball-by-ball details.
410
+ details_url: str
411
+ #: ESPN site API summary URL.
412
+ espn_api_url: str
413
+ #: The parsed page, reshaped by ``_normalize``. Prefer the attributes.
414
+ json: dict[str, Any]
415
+
416
+ def __init__(self, match_id: int | str, series_id: int | str) -> None:
417
+ """Fetch and parse the match.
418
+
419
+ Args:
420
+ match_id: ESPNcricinfo match (event) id.
421
+ series_id: ESPNcricinfo series (league) id the match belongs to.
422
+ """
423
+ self.match_id = int(match_id)
424
+ self.series_id = int(series_id)
425
+ self.json = self._get_json()
426
+ data = self.json
427
+ match = data["match"]
428
+ series = data["series"][-1]
429
+
430
+ self.series_id = int(series["core_recreation_id"])
431
+ self.description = data["description"]
432
+ self.match_title = match["cms_match_title"]
433
+ self.match_class = (
434
+ match["international_class_card"] or match["general_class_card"]
435
+ )
436
+ self.status = match["match_status"]
437
+ self.result = data["live"]["status"]
438
+ self.season = match["season"]
439
+ self.series_name = series["series_name"] or None
440
+ self.date = match["start_date_raw"]
441
+ self.start_datetime = match["start_datetime_gmt"]
442
+ self.canceled = match["cancelled_match"] != "N"
443
+ self.ground_id = match["ground_id"]
444
+ self.ground_name = match["ground_name"]
445
+ self.town_name = match.get("town_name")
446
+ self.lighting = match["floodlit_name"]
447
+ overs = match.get("scheduled_overs")
448
+ self.scheduled_overs = int(overs) if overs is not None else None
449
+ self.innings_list = data["centre"]["common"]["innings_list"]
450
+ self.innings = data["innings"]
451
+ self.all_innings = data.get("_content", {}).get("innings", self.innings)
452
+ self.rosters = data.get("_match_players")
453
+
454
+ self.team_1, self.team_2 = data["team"][0], data["team"][1]
455
+ self.team_1_id = self.team_1["team_id"]
456
+ self.team_2_id = self.team_2["team_id"]
457
+ self.team_1_abbreviation = self.team_1["team_abbreviation"]
458
+ self.team_2_abbreviation = self.team_2["team_abbreviation"]
459
+ self.team_1_players = self.team_1.get("player", [])
460
+ self.team_2_players = self.team_2.get("player", [])
461
+ self.team_1_innings = self._first_innings_of(self.team_1_id)
462
+ self.team_2_innings = self._first_innings_of(self.team_2_id)
463
+ self.team_1_run_rate = _as_float(self.team_1_innings, "run_rate")
464
+ self.team_2_run_rate = _as_float(self.team_2_innings, "run_rate")
465
+ self.team_1_overs_batted = _as_float(self.team_1_innings, "overs")
466
+ self.team_2_overs_batted = _as_float(self.team_2_innings, "overs")
467
+
468
+ self.home_team = self._abbreviation(match.get("home_team_id"))
469
+ self.batting_first = self._abbreviation(match.get("batting_first_team_id"))
470
+ self.match_winner = self._abbreviation(match.get("winner_team_id"))
471
+ toss_winner = match.get("toss_winner_team_id") or None
472
+ self.toss_winner = toss_winner
473
+ self.toss_decision_name = (
474
+ match.get("toss_decision_name") or None if toss_winner else None
475
+ )
476
+
477
+ self.event_url = (
478
+ "http://core.espnuk.org/v2/sports/cricket/leagues/"
479
+ f"{self.series_id}/events/{self.match_id}"
480
+ )
481
+ self.details_url = (
482
+ f"{self.event_url}/competitions/{self.match_id}/details"
483
+ "?page_size=1000&page=1"
484
+ )
485
+ self.espn_api_url = (
486
+ "https://site.api.espn.com/apis/site/v2/sports/cricket/"
487
+ f"{self.series_id}/summary?event={self.match_id}"
488
+ )
489
+
490
+ def __str__(self) -> str:
491
+ """Return the match description."""
492
+ return self.description
493
+
494
+ def __repr__(self) -> str:
495
+ """Return ``Match(match_id, series_id)``."""
496
+ return f"{self.__class__.__name__}({self.match_id!r}, {self.series_id!r})"
497
+
498
+ def _get_json(self) -> dict[str, Any]:
499
+ """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)
505
+
506
+ def _first_innings_of(self, team_id: str) -> dict[str, Any] | None:
507
+ return next(
508
+ (inn for inn in self.innings if inn["batting_team_id"] == team_id), None
509
+ )
510
+
511
+ def _abbreviation(self, team_id: str | None) -> str | None:
512
+ """Map a team id to its abbreviation; None when ESPN gives no team."""
513
+ teams = {
514
+ self.team_1_id: self.team_1_abbreviation,
515
+ self.team_2_id: self.team_2_abbreviation,
516
+ }
517
+ return teams.get(team_id or "")
518
+
519
+ def _innings_field(self, innings: int, field: str) -> Any:
520
+ try:
521
+ return self.innings[innings - 1][field]
522
+ except (IndexError, KeyError):
523
+ return None
524
+
525
+ def batsmen(self, innings: int) -> list[dict[str, Any]] | None:
526
+ """ESPN's raw batting records for a 1-based innings, or None."""
527
+ return self._innings_field(innings, "inningBatsmen")
528
+
529
+ def bowlers(self, innings: int) -> list[dict[str, Any]] | None:
530
+ """ESPN's raw bowling records for a 1-based innings, or None."""
531
+ return self._innings_field(innings, "inningBowlers")
532
+
533
+ def fows(self, innings: int) -> list[dict[str, Any]] | None:
534
+ """ESPN's raw fall-of-wicket records for a 1-based innings, or None."""
535
+ return self._innings_field(innings, "inningFallOfWickets")
536
+
537
+ def extras(self, innings: int) -> dict[str, int | None] | None:
538
+ """Extras for a 1-based innings: total, byes, leg byes, wides, no balls."""
539
+ if not 1 <= innings <= len(self.innings):
540
+ return None
541
+ inn = self.innings[innings - 1]
542
+ return {
543
+ key: inn.get(key)
544
+ for key in ("extras", "byes", "legbyes", "wides", "noballs")
545
+ }
546
+
547
+ # ------------------------------------------------------------------
548
+ # Scorecard helpers
549
+ # ------------------------------------------------------------------
550
+
551
+ def _batting_entry(self, raw: dict[str, Any]) -> BattingEntry:
552
+ """Transform a raw inningBatsmen dict into a clean flat dict."""
553
+ player = raw.get("player") or {}
554
+ batted = raw.get("battedType") == "yes"
555
+ is_out = bool(raw.get("isOut"))
556
+ if not batted:
557
+ dismissal = "did not bat"
558
+ elif is_out:
559
+ dismissal = (raw.get("dismissalText") or {}).get("long", "out")
560
+ else:
561
+ dismissal = "not out"
562
+ return {
563
+ "name": player.get("name"),
564
+ "full_name": player.get("longName"),
565
+ "player_id": player.get("objectId"),
566
+ "runs": raw.get("runs") if batted else None,
567
+ "balls": raw.get("balls") if batted else None,
568
+ "minutes": raw.get("minutes") if batted else None,
569
+ "fours": raw.get("fours") if batted else None,
570
+ "sixes": raw.get("sixes") if batted else None,
571
+ "strike_rate": float(sr)
572
+ if (batted and (sr := raw.get("strikerate")) is not None)
573
+ else None,
574
+ "is_out": is_out,
575
+ "dismissal": dismissal,
576
+ "batted": batted,
577
+ }
578
+
579
+ @property
580
+ def batting_scorecard(self) -> list[list[BattingEntry]]:
581
+ """Batting scorecard: one list per innings, one row per batter.
582
+
583
+ Outer list is indexed by innings order; inner list has one entry
584
+ per batsman. Players who did not bat have ``batted=False`` and
585
+ numeric fields as ``None``.
586
+
587
+ Example::
588
+
589
+ for i, innings in enumerate(m.batting_scorecard, 1):
590
+ print(f"Innings {i}:")
591
+ for b in innings:
592
+ print(b["name"], b["runs"], b["balls"], b["dismissal"])
593
+ """
594
+ result = []
595
+ for i in range(1, len(self.innings) + 1):
596
+ raw_list = self.batsmen(i)
597
+ if raw_list:
598
+ result.append([self._batting_entry(r) for r in raw_list])
599
+ else:
600
+ result.append([])
601
+ return result
602
+
603
+ def _bowling_entry(self, raw: dict[str, Any]) -> BowlingEntry:
604
+ """Transform a raw inningBowlers dict into a clean flat dict."""
605
+ player = raw.get("player") or {}
606
+ economy = raw.get("economy")
607
+ overs = raw.get("overs")
608
+ return {
609
+ "name": player.get("name"),
610
+ "full_name": player.get("longName"),
611
+ "player_id": player.get("objectId"),
612
+ "overs": float(overs) if overs is not None else None,
613
+ "maidens": raw.get("maidens"),
614
+ "runs": raw.get("conceded"),
615
+ "wickets": raw.get("wickets"),
616
+ "economy": float(economy) if economy is not None else None,
617
+ "wides": raw.get("wides"),
618
+ "no_balls": raw.get("noballs"),
619
+ "dots": raw.get("dots"),
620
+ }
621
+
622
+ @property
623
+ def bowling_scorecard(self) -> list[list[BowlingEntry]]:
624
+ """Bowling scorecard: one list per innings, one row per bowler.
625
+
626
+ Outer list is indexed by innings order; inner list has one entry
627
+ per bowler.
628
+
629
+ Example::
630
+
631
+ for i, innings in enumerate(m.bowling_scorecard, 1):
632
+ print(f"Innings {i}:")
633
+ for b in innings:
634
+ print(b["name"], b["wickets"], b["runs"], b["overs"])
635
+ """
636
+ result = []
637
+ for i in range(1, len(self.innings) + 1):
638
+ raw_list = self.bowlers(i)
639
+ if raw_list:
640
+ result.append([self._bowling_entry(r) for r in raw_list])
641
+ else:
642
+ result.append([])
643
+ return result
644
+
645
+ # ------------------------------------------------------------------
646
+ # Static helpers
647
+ # ------------------------------------------------------------------
648
+
649
+ @staticmethod
650
+ def get_recent_matches(date: _date | str | None = None) -> list[MatchRef]:
651
+ """Return MatchRefs for the matches on ESPNcricinfo's results page.
652
+
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.
657
+
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.
661
+ """
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}"
675
+ )
676
+
677
+ next_data = _playwright_fetch(url)
678
+ 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