-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcricbuzz.py
1060 lines (1017 loc) · 44.8 KB
/
cricbuzz.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import requests
from bs4 import BeautifulSoup
class Cricbuzz:
"""
## Cricbuzz class to get live matches, recent matches, upcoming matches, match stats and info, series info, series stats and info, team info, team stats and info, player info, player stats and info, etc.\n
### Parameters - None\n
### Methods - \n
get_live_matches(type) - Returns a list of live matches\n
get_recent_matches(type) - Returns a list of recent matches\n
get_upcoming_matches(type) - Returns a list of upcoming matches\n
get_series(type) - Returns a dictionary of series in month and year format\n
get_series_from_archive(year, type) - Returns a list of series from archive\n
get_matches_by_day(type) - Returns a dictionary of matches by day\n
get_series_matches(series_id) - Returns a list of matches in a series\n
get_series_stats(series_id, match_format, stat) - Returns a list of stats of players in a series\n
get_teams_list(type) - Returns a list of teams\n
get_team_schedule(team_id) - Returns a list of matches of a team\n
get_team_players(team_id) - Returns a list of players of a team\n
get_team_results(team_id) - Returns a list of past results of a team\n
get_team_stats(team_id, year, match_format, stat) - Returns a list of player stats of a team\n
#### Future Plans: Implement Player Stats, Series Squads, Series Venues
"""
BASE_URL = "https://www.cricbuzz.com/"
TYPES = ["all", "international", "domestic", "league", "women"]
FORMATS = ["Test", "ODI", "T20I"]
STATS = [
"most-runs",
"highest-score",
"highest-avg",
"highest-sr",
"most-hundreds",
"most-fifties",
"most-fours",
"most-sixes",
"most-nineties",
"most-wickets",
"lowest-avg",
"best-bowling-innnings",
"most-five-wickets",
"lowest-econ",
"lowest-sr",
]
def __init__(self):
self.session = requests.Session()
def __timestamp_to_date(self, timestamp):
"""
Converts timestamp to date
"""
from datetime import datetime
dt_obj = datetime.utcfromtimestamp(timestamp / 1000)
return dt_obj.strftime("%d-%m-%Y %H:%M:%S")
def __scrape_match(self, url, type, isUpcoming=False):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
search_paras = {
"class": "cb-col cb-col-100 cb-plyr-tbody cb-rank-hdr cb-lv-main"
}
if type.lower() not in self.TYPES:
return [{"error": "Invalid type"}]
elif type.lower() != "all":
search_paras["ng-show"] = f"active_match_type == '{type.lower()}-tab'"
series = soup.find_all(
"div",
attrs=search_paras,
)
if len(series) == 0:
return [{"error": "No live matches"}]
matches = []
for s in series:
series_name = s.find("h2").text.strip()
series_matches = s.find_all(
"div", attrs={"class": "cb-mtch-lst cb-col cb-col-100 cb-tms-itm"}
)
for m in series_matches:
match_data = {}
match_data["series_name"] = series_name
match_data["match_name"] = (
m.find(
"h3", class_="cb-lv-scr-mtch-hdr inline-block"
).text.strip()
+ " "
+ m.find("span", class_="text-gray").text.strip()
)
match_data["start_date_time"] = (
self.__timestamp_to_date(
int(
m.find("div", class_="text-gray")
.find("span")["ng-if"]
.split("|")[0]
.strip()[1:]
)
)
+ " GMT"
)
match_data["location"] = "at".join(
m.find("div", class_="text-gray")
.find_all("span")[-1]
.text.split("at")[1:]
).strip()
match_data_id = m.find("a")["href"].split("/")
match_id = match_data_id[
match_data_id.index("live-cricket-scores") + 1
]
match_data["match_id"] = match_id
if not isUpcoming:
match_data["status"] = m.find("div", class_="cb-text-live")
if match_data["status"] == None:
match_data["status"] = m.find(
"div", class_="cb-text-complete"
)
if match_data["status"] == None:
match_data["status"] = m.find(
"div", class_="cb-text-preview"
)
if match_data["status"] != None:
match_data["status"] = match_data["status"].text.strip()
else:
del match_data["status"]
match_score = []
score_div = m.find(
"div", class_="cb-scr-wll-chvrn cb-lv-scrs-col"
)
if score_div == None:
matches.append(match_data)
continue
bat_scores_div = score_div.find(
"div", class_="cb-hmscg-bat-txt"
)
bowl_scores_div = score_div.find(
"div", class_="cb-hmscg-bwl-txt"
)
if bat_scores_div == None and bowl_scores_div == None:
matches.append(match_data)
continue
elif bat_scores_div == None:
bat_scores_div = score_div.find_all(
"div", class_="cb-hmscg-bwl-txt"
)[1]
elif bowl_scores_div == None:
bowl_scores_div = score_div.find_all(
"div", class_="cb-hmscg-bat-txt"
)[1]
bat_team_names = bat_scores_div.find(
"div", class_="cb-hmscg-tm-nm"
).text.strip()
bowl_team_names = bowl_scores_div.find(
"div", class_="cb-hmscg-tm-nm"
).text.strip()
bat_scores = bat_scores_div.find_all(
"div", class_="cb-ovr-flo"
)[-1].text.strip()
bowl_scores = bowl_scores_div.find_all(
"div", class_="cb-ovr-flo"
)[-1].text.strip()
bat_team_scores = {
"team_name": bat_team_names,
"scores": [i.strip() for i in bat_scores.split("&")],
}
bowl_team_scores = {
"team_name": bowl_team_names,
"scores": [i.strip() for i in bowl_scores.split("&")],
}
match_score.append(bat_team_scores)
match_score.append(bowl_team_scores)
match_data["score"] = match_score
matches.append(match_data)
return matches
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_live_matches(self, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_live_matches(type)\n
## Parameters -
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - list of live matches\n
## Data Format - \n
```python
[{"series_name": {series_name},"match_name": {match_name},"start_date_time": {start_date_time},"location": {location},"match_id": {match_id},"status": {status},"score": [{team_name: {team_name}, "scores": [{score1}, {score2}, ...]}, {team_name: {team_name}, "scores": [{score1}, {score2}, ...]}]},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
live_matches = cricbuzz.get_live_matches(type="international")
for match in live_matches:
print(match["match_name"], end="\t")
print(match["status"])
```
## Output - \n
```text
{match_name} {match_status}
{match_name} {match_status}
{match_name} {match_status}....
```
"""
URL = self.BASE_URL + "cricket-match/live-scores"
return self.__scrape_match(url=URL, type=type)
def get_recent_matches(self, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_recent_matches(type)\n
## Parameters -
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - list of recent matches\n
## Data Format - \n
```python
[{"series_name": {series_name},"match_name": {match_name},"start_date_time": {start_date_time},"location": {location},"match_id": {match_id},"status": {status}, "score": [{team_name: {team_name}, "scores": [{score1}, {score2}, ...]}, {team_name: {team_name}, "scores": [{score1}, {score2}, ...]}]},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
recent_matches = cricbuzz.get_recent_matches(type="international")
for match in recent_matches:
print(match["match_name"], end="\t")
print(match["status"])
```
## Output - \n
```text
{match_name} {match_status}
{match_name} {match_status}
{match_name} {match_status}....
```
"""
URL = self.BASE_URL + "cricket-match/live-scores/recent-matches"
return self.__scrape_match(url=URL, type=type)
def get_upcoming_matches(self, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_upcoming_matches(type)\n
## Parameters -
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - list of recent matches\n
## Data Format - \n
```python
[{"series_name": {series_name},"match_name": {match_name},"start_date_time": {start_date_time},"location": {location},"match_id": {match_id}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
upcoming_matches = cricbuzz.get_upcoming_matches(type="international")
for match in upcoming_matches:
print(match["match_name"], end="\t")
print(match["status"])
```
## Output - \n
```text
{match_name} {match_status}
{match_name} {match_status}
{match_name} {match_status}....
```
"""
URL = self.BASE_URL + "cricket-match/live-scores/upcoming-matches"
return self.__scrape_match(url=URL, type=type, isUpcoming=True)
def __scrape_series(self, url, type="all"):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
series = soup.find_all(
"div",
class_="cb-col-100 cb-col",
)
international_series = [
i
for i in series
if i["ng-if"] == "((filtered_category == 0 || filtered_category == 9))"
]
domestic_series = [
i
for i in series
if i["ng-if"] == "((filtered_category == 1 || filtered_category == 9))"
]
league_series = [
i
for i in series
if i["ng-if"] == "((filtered_category == 2 || filtered_category == 9))"
]
womens_series = [
i
for i in series
if i["ng-if"] == "((filtered_category == 3 || filtered_category == 9))"
]
diff_series = [
international_series,
domestic_series,
league_series,
womens_series,
]
if type.lower() not in self.TYPES:
return [{"error": "Invalid type"}]
elif type.lower() != "all":
series = diff_series[self.TYPES.index(type.lower()) - 1]
series_data = {}
for s in series:
series_month = s.find(
"div", class_="cb-col-16 cb-col text-bold cb-mnth"
)
monthly_series_data = []
series_div = s.find_all("div", class_="cb-sch-lst-itm")
for i in series_div:
series_data_id = i.find("a")["href"].split("/")
series_id = series_data_id[
series_data_id.index("cricket-series") + 1
]
monthly_series_data.append(
{
"series_name": i.find("a").text.strip(),
"series_id": series_id,
"series_dates": i.find(
"div", class_="text-gray cb-font-12"
).text.strip(),
}
)
if series_data.get(series_month.text.strip()) == None:
series_data[series_month.text.strip()] = monthly_series_data
else:
series_data[series_month.text.strip()].extend(monthly_series_data)
return series_data
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_series(self, type="all"):
"""
## Class - Cricbuzz\n
## get_series(type)\n
## Parameters -
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - dictionary of series in month and year format\n
## Data Format - \n
```python
{"month year" : [{"series_name": {series_name},"series_id": {series_id},"series_dates": {series_dates}},]}
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
cric_series = cricbuzz.get_series(type="international")
for series in cric_series:
print(series)
for matches in cric_series[series]:
print("\t", matches["series_name"], end="\t")
print("\t", matches["series_dates"])
```
## Output - \n
```text
{month} {year}
{series_name} {series_dates}
{series_name} {series_dates} ....
{month} {year}
{series_name} {series_dates}
{series_name} {series_dates} ....
{month} {year}....
```
"""
URL = self.BASE_URL + "cricket-schedule/series"
return self.__scrape_series(url=URL, type=type)
def __scrape_series_from_archive(self, url, type="all"):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.select_one(
"#page-wrapper > div:nth-child(5) > div.cb-left.cb-col-67.cb-col.cb-schdl"
)
data_elements = [
i.text.lower()
for i in data.find_all(
"h2",
class_="cb-col-16 cb-col text-bold cb-srs-cat cb-lv-scr-mtch-hdr",
)
]
data_divs = data.find_all("div", class_="cb-col-84 cb-col")
divs = data_divs
if type.lower() != "all":
if type.lower() == "league":
divs = [data_divs[data_elements.index("t20 league")]]
else:
divs = [data_divs[data_elements.index(type.lower())]]
series = []
for d in divs:
data = []
series_data = d.find_all("div", class_="cb-srs-lst-itm")
for s in series_data:
series_data_id = s.find("a")["href"].split("/")
series_id = series_data_id[
series_data_id.index("cricket-series") + 1
]
data.append(
{
"series_name": s.find("a").text.strip(),
"series_id": series_id,
"series_dates": s.find(
"span", class_="text-gray cb-font-12"
).text.strip(),
}
)
series.extend(data)
return series
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_series_from_archive(self, year, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_series_from_archive(year, type)\n
## Parameters -
(required) year (int) \n
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - list of series from archive\n
## Data Format - \n
```python
[{"series_name": {series_name},"series_id": {series_id},"series_dates": {series_dates}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
cric_series = cricbuzz.get_series_from_archive(year=2023, type="international")
for series in cric_series:
print(series["series_name"], end="\t")
print(series["series_dates"])
```
## Output - \n
```text
{series_name} {series_dates}
{series_name} {series_dates} ....
{series_name} {series_dates} ....
```
"""
URL = self.BASE_URL + f"cricket-scorecard-archives/{year}"
if type.lower() not in self.TYPES:
return [{"error": "Invalid type"}]
return self.__scrape_series_from_archive(url=URL, type=type)
def __scarpe_matches_by_day(self, url, type):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.find("div", id=f"{type.lower()}-list")
days_data = data.select(f"#{type.lower()}-list > div:nth-child(n)")
matches_data = {}
for i in days_data:
day = i.find("div", class_="cb-lv-grn-strip text-bold").text.strip()
match_data = i.find_all("div", class_="cb-col-100 cb-col")
matches = []
for m in match_data:
match_data = {}
match_series = m.find("a")
match_series_data_id = match_series["href"].split("/")
match_data["series_name"] = match_series.text.strip()
match_data["series_id"] = match_series_data_id[
match_series_data_id.index("cricket-series") + 1
]
match_elem = m.find("div", class_="cb-col-67 cb-col").find("a")
match_data_id = match_elem["href"].split("/")
match_data["match_name"] = match_elem.text.strip()
match_data["match_id"] = match_data_id[
match_data_id.index("live-cricket-scores") + 1
]
match_data["location"] = m.find(
"div", attrs={"itemprop": "location"}
).text.strip()
match_data["start_date_time"] = (
self.__timestamp_to_date(
int(m.find("span", class_="schedule-date")["timestamp"])
)
+ " GMT"
)
matches.append(match_data)
matches_data[day] = matches
return matches_data
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_matches_by_day(self, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_matches_by_day(type)\n
## Parameters -
(optional) type (str) \t Available Paramaters -> ["all", "international", "domestic", "league", "women"]\n
## Returns - dictionary of matches by day\n
## Data Format -\n
```python
{"day" : [{"series_name": {series_name},"series_id": {series_id},"match_name": {match_name},"match_id": {match_id},"location": {location},"start_date_time": {start_date_time}},]}
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
cric_series = cricbuzz.get_matches_by_day(type="international")
for day in cric_series:
print(day)
for match in cric_series[day]:
print("\t", match["match_name"], end="\t")
print("\t", match["start_date_time"])
```
## Output - \n
```text
{day}
{match_name} {start_date_time}
{match_name} {start_date_time} ....
{day}
{match_name} {start_date_time}
{match_name} {start_date_time} ....
{day}....
```
"""
URL = self.BASE_URL + "cricket-schedule/upcoming-series"
if type.lower() not in self.TYPES:
return [{"error": "Invalid type"}]
else:
URL += f"/{type.lower()}"
return self.__scarpe_matches_by_day(url=URL, type=type)
def __scrape_series_matches(self, url):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.find_all("div", class_="cb-series-matches")
matches = []
for m in data:
match_data = {}
match_data["match_start_data_time"] = (
self.__timestamp_to_date(
int(
m.find("div", class_="schedule-date")
.find("span")["ng-bind"]
.split("|")[0]
.strip()
)
)
+ " GMT"
)
match_data["match_title"] = (
m.find("div", class_="cb-col-60 cb-col cb-srs-mtchs-tm")
.find("span")
.text.strip()
)
match_data["match_location"] = (
m.find("div", class_="cb-col-60 cb-col cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.text.strip()
)
if (
m.find("div", class_="cb-col-60 cb-col cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
is not None
):
match_data["match_status"] = (
m.find("div", class_="cb-col-60 cb-col cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
.text.strip()
)
match_id_data = m.find("a")["href"].split("/")
try:
match_data["match_id"] = match_id_data[
match_id_data.index("cricket-scores") + 1
]
except:
match_data["match_id"] = match_id_data[
match_id_data.index("live-cricket-scores") + 1
]
matches.append(match_data)
return matches
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_series_matches(self, series_id):
"""
## Class - Cricbuzz\n
## Method - get_series_matches(series_id)\n
## Parameters -
(required) series_id (int)\n
## Returns - list of matches in a series\n
## Data Format -\n
```python
[{"match_start_data_time": {match_start_data_time},"match_title": {match_title},"match_location": {match_location},"match_status": {match_status},"match_id": {match_id}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
cric_series_matches = cricbuzz.get_series_matches(6351)
for match in cric_series_matches:
print(match["match_title"])
```
## Output - \n
```text
{match_title}
{match_title}
{match_title}....
```
"""
URL = self.BASE_URL + f"cricket-series/{series_id}/series/matches"
return self.__scrape_series_matches(url=URL)
def __scrape_series_stats(self, series_id, match_format="Test", stat="most-runs"):
try:
format_index = self.FORMATS.index(match_format) + 1
URL = f"https://www.cricbuzz.com/api/html/series/{series_id}/{stat}/{format_index}/0/0"
res = self.session.get(URL)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
if soup.find("tbody") == None:
return {"error": "No data found"}
keys = [i.text.strip() for i in soup.find("thead").find_all("th")]
players_data = soup.find("tbody").find_all("tr")
players = []
for i in players_data:
player_data_id = i.find("a")["href"].split("/")
player_id = player_data_id[player_data_id.index("profiles") + 1]
player_data = [i.text.strip() for i in i.find_all("td")]
player_data_dict = dict(zip(keys, player_data))
player_data_dict["PLAYER ID"] = player_id
players.append(player_data_dict)
return players
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_series_stats(self, series_id, match_format="Test", stat="most-runs"):
"""
## Class - Cricbuzz\n
## Method - get_series_stats(series_id, match_format, stat)\n
## Parameters -\n
(required) series_id (int)\n
(optional) match_format (str) \t - Available Formats -> ["Test", "ODI", "T20I"]
(optional) stat (str) \t - Available Stats -> ["most-runs","highest-score","highest-avg","highest-sr","most-hundreds","most-fifties","most-fours","most-sixes","most-nineties","most-wickets","lowest-avg","best-bowling-innnings","most-five-wickets","lowest-econ","lowest-sr",]\n
## Returns - list of stats of players in a series\n
## Data Format -\n
```python
[{"":{S.No}, "Player": {Player_Name}, "Matches": {Matches}, "Innings": {Innings}, "PLAYER ID": {Player_ID}, ...(different stats)},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
player_stats = cricbuzz.get_series_stats(6351)
for player in player_stats:
print(player["Player"], end="\t")
print(player["Runs"])
```
## Output - \n
```text
{Player_Name} {Runs}
{Player_Name} {Runs}
{Player_Name} {Runs}....
```
"""
if match_format not in self.FORMATS:
return [{"error": "Invalid match format", "valid_formats": self.FORMATS}]
if stat not in self.STATS:
return [{"error": "Invalid stat", "valid_stats": self.STATS}]
return self.__scrape_series_stats(
series_id=series_id, match_format=match_format, stat=stat
)
def __scrape_team_data(self, url):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.select_one(
"#page-wrapper > div:nth-child(6) > div.cb-col.cb-col-67.cb-nws-lft-col > div.cb-col.cb-col-100"
)
teams = []
teams_data = data.find_all("div", class_="cb-team-item")
for t in teams_data:
team_name = t.find("a")["title"].strip().title()
team_code = t.find("a")["href"].split("/")[-1].strip()
teams.append({"team_name": team_name, "team_code": team_code})
return teams
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_teams_list(self, type="all"):
"""
## Class - Cricbuzz\n
## Method - get_teams_list(type)\n
## Parameters -\n
(optional) type (str) \t - Available Types -> ["all", "international", "domestic", "league", "women"]\n
## Returns - list of teams\n
## Data Format -\n
```python
[{"team_name": {team_name}, "team_code": {team_code}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
teams = cricbuzz.get_teams_list(type="international")
for team in teams:
print(team["team_name"], end="-")
print(team["team_code"])
```
## Output - \n
```text
{team_name}-{team_code}
{team_name}-{team_code}
{team_name}-{team_code}....
```
"""
URL = self.BASE_URL + "cricket-team"
if type.lower() not in self.TYPES:
return [{"error": "Invalid type"}]
elif type.lower() != "all" and type.lower() != "international":
URL += f"/{type.lower()}"
if type.lower() == "all":
return {
"international": self.__scrape_team_data(url=URL),
"domestic": self.__scrape_team_data(url=URL + "/domestic"),
"league": self.__scrape_team_data(url=URL + "/league"),
"women": self.__scrape_team_data(url=URL + "/women"),
}
return self.__scrape_team_data(url=URL)
def __scrape_team_schedule(self, url):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.find_all("div", class_="cb-series-matches")
matches = []
for m in data:
match_data = {}
match_data["match_start_data_time"] = (
self.__timestamp_to_date(
int(
m.find("div", class_="schedule-date")
.find("span")["ng-bind"]
.split("|")[0]
.strip()
)
)
+ " GMT"
)
match_data["match_title"] = (
m.find("div", class_="cb-srs-mtchs-tm").find("span").text.strip()
)
match_data["match_location"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray cb-ovr-flo")
.text.strip()
)
match_data["match_series_name"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.text.strip()
)
if (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
is not None
):
match_data["match_status"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
.text.strip()
)
match_id_data = m.find("a")["href"].split("/")
try:
match_data["match_id"] = match_id_data[
match_id_data.index("cricket-scores") + 1
]
except:
match_data["match_id"] = match_id_data[
match_id_data.index("live-cricket-scores") + 1
]
matches.append(match_data)
return matches
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_team_schedule(self, team_id):
"""
## Class - Cricbuzz\n
## Method - get_team_schedule(team_id)\n
## Parameters -\n
(required) team_id (int)
## Returns - list of matches of a team\n
## Data Format -\n
```python
[{"match_start_data_time": {match_start_data_time},"match_title": {match_title},"match_location": {match_location},"match_series_name": {match_series_name},"match_status": {match_status},"match_id": {match_id}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
team_schedule = cricbuzz.get_team_schedule(2)
for match in team_schedule:
print(match["match_title"])
```
## Output - \n
```text
{match_title}
{match_title}
{match_title}....
```
"""
URL = self.BASE_URL + f"cricket-team/team/{team_id}/schedule"
return self.__scrape_team_schedule(url=URL)
def __scrape_team_players(self, url):
# try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
players_data = soup.find("div", class_="cb-top-zero").find_all(
"a", class_="cb-col cb-col-50"
)
players = []
for player in players_data:
player_data_id = player["href"].split("/")
player_id = player_data_id[player_data_id.index("profiles") + 1]
players.append(
{
"player_name": player.text.strip(),
"player_id": player_id,
}
)
return players
def get_team_players(self, team_id):
"""
## Class - Cricbuzz\n
## Method - get_team_players(team_id)\n
## Parameters -\n
(required) team_id (int)
## Returns - list of players of a team\n
## Data Format -\n
```python
[{"player_name": {player_name},"player_id": {player_id}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
team_players = cricbuzz.get_team_players(2)
for player in team_players:
print(player["player_name"])
```
## Output - \n
```text
{player_name}
{player_name}
{player_name}....
```
"""
URL = self.BASE_URL + f"cricket-team/team/{team_id}/players"
return self.__scrape_team_players(url=URL)
def __scrape_team_results(self, url):
try:
res = self.session.get(url)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
data = soup.find("div", id="series-matches").find_all(
"div", class_="cb-col-100 cb-col cb-brdr-thin-btm"
)
matches = []
for m in data:
match_data = {}
match_data["match_start_data_time"] = (
self.__timestamp_to_date(
int(m.find("span")["ng-bind"].split("|")[0].strip())
)
+ " GMT"
)
match_data["match_title"] = (
m.find("div", class_="cb-srs-mtchs-tm").find("a").text.strip()
)
match_data["match_series_name"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.text.strip()
)
if (
len(
m.find("div", class_="cb-srs-mtchs-tm").find_all(
"div", class_="text-gray"
)
)
> 1
):
match_data["match_location"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find_all("div", class_="text-gray")[1]
.text.strip()
)
if (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
is not None
):
match_data["match_status"] = (
m.find("div", class_="cb-srs-mtchs-tm")
.find("div", class_="text-gray")
.find_next_sibling("a")
.text.strip()
)
match_id_data = m.find("a")["href"].split("/")
try:
match_data["match_id"] = match_id_data[
match_id_data.index("cricket-scores") + 1
]
except:
match_data["match_id"] = match_id_data[
match_id_data.index("live-cricket-scores") + 1
]
matches.append(match_data)
return matches
except Exception as e:
return [{"error": f"Something Went Wrong: {e}"}]
def get_team_results(self, team_id):
"""
## Class - Cricbuzz\n
## Method - get_team_results(team_id)\n
## Parameters -\n
(required) team_id (int)
## Returns - list of past results of a team\n
## Data Format -\n
```python
[{"player_name": {player_name},"player_id": {player_id}},]
```
## Example - \n
```python
from scrape_up.cricbuzz import Cricbuzz
cricbuzz = Cricbuzz()
team_results = cricbuzz.get_team_results(2)
for result in team_results:
print(result["match_status"])
```
## Output - \n
```text
{match_status}
{match_status}
{match_status}....
```
"""
URL = self.BASE_URL + f"cricket-team/team/{team_id}/results"
return self.__scrape_team_results(url=URL)
def __scrape_team_stats(self, team_id, year, match_format="Test", stat="most-runs"):
try:
format_index = self.FORMATS.index(match_format) + 1
URL = f"https://www.cricbuzz.com/cricket-team/team/{team_id}/stats-table/{stat}/{format_index}/{year}/all"
res = self.session.get(URL)
if res.status_code != 200:
return [{"error": "Unable to fetch data from cricbuzz"}]
soup = BeautifulSoup(res.text, "html.parser")
if soup.find("tbody") == None:
return {"error": "No data found"}
keys = [i.text.strip() for i in soup.find("thead").find_all("th")]
players_data = soup.find("tbody").find_all("tr")
players = []
for i in players_data:
player_data_id = i.find("a")["href"].split("/")
player_id = player_data_id[player_data_id.index("profiles") + 1]