-
Notifications
You must be signed in to change notification settings - Fork 0
/
IMDb.py
executable file
·356 lines (289 loc) · 11.2 KB
/
IMDb.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
#!/usr/bin/env python3
"""
IMDb Top Movies/TV Shows Data Scraper
Original Post: https://medium.com/@nishantsahoo/which-movie-should-i-watch-5c83a3c0f5b1
Author: Jugal Kishore
Version: 3.0
"""
import json
import os
import subprocess
import sys
from datetime import datetime
from requests import get
from bs4 import BeautifulSoup
# Original post link
ORIGINAL_POST_URL = (
"https://medium.com/@nishantsahoo/which-movie-should-i-watch-5c83a3c0f5b1"
)
# Get current year
CURRENT_YEAR = datetime.now().year
# IMDb URLs
IMDB_BASE_URL = "https://www.imdb.com"
IMDB_MOVIES_SEARCH_URL = f"https://www.imdb.com/search/title/?title_type=feature&release_date={CURRENT_YEAR}-01-01,{CURRENT_YEAR}-12-31"
IMDB_TOP_250_MOVIES_URL = "https://www.imdb.com/chart/top/"
IMDB_POPULAR_MOVIES_URL = "https://www.imdb.com/chart/moviemeter/"
IMDB_TV_SEARCH_URL = f"https://www.imdb.com/search/title/?title_type=tv_series&release_date={CURRENT_YEAR}-01-01,{CURRENT_YEAR}-12-31"
IMDB_TOP_250_TV_URL = "https://www.imdb.com/chart/toptv/"
IMDB_POPULAR_TV_URL = "https://www.imdb.com/chart/tvmeter/"
# Custom headers
HEADERS = {
"user-agent": "Mozilla/5.0 (X11; Linux x86_64; rv:130.0) Gecko/20100101 Firefox/130.0"
}
def fetch_popular_movies() -> list[dict]:
"""
Fetch information about popular Movies from IMDb.
Returns:
list of dict: A list where each dictionary contains Movie information,
such as the Movie's name, link, and rating.
"""
print(
f"Fetching Popular Movies {CURRENT_YEAR} from IMDb ->", IMDB_POPULAR_MOVIES_URL
)
movie_data = []
response = get(IMDB_POPULAR_MOVIES_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = json.loads(soup.find("script", type="application/ld+json").text)
for movie in json_data["itemListElement"]:
movie_name = movie["item"]["name"]
try:
movie_rating = movie["item"]["aggregateRating"]["ratingValue"]
except KeyError:
movie_rating = 0
movie_link = movie["item"]["url"]
movie_data.append(
{"name": movie_name, "rating": movie_rating, "link": movie_link}
)
return movie_data
def fetch_top_50_movies() -> list[dict]:
"""
Fetch information about the Top 50 Movies of the current year from IMDb.
Returns:
list of dict: A list where each dictionary contains Movie information,
such as the Movie's name and link.
"""
print(
f"Fetching Top 50 Movies {CURRENT_YEAR} from IMDb ->", IMDB_MOVIES_SEARCH_URL
)
movie_data = []
response = get(IMDB_MOVIES_SEARCH_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = (
json.loads(soup.find("script", id="__NEXT_DATA__").text)
.get("props", {})
.get("pageProps", {})
.get("searchResults", {})
.get("titleResults", {})
.get("titleListItems")
)
for movie in json_data:
movie_data.append(
{
"name": movie["originalTitleText"],
"link": IMDB_BASE_URL + "/title/" + movie["titleId"] + "/",
"rating": movie["ratingSummary"]["aggregateRating"],
}
)
return movie_data
def fetch_top_250_movies():
"""
Fetch the Top 250 Movies from IMDb and save them to a CSV file.
"""
print(f"Fetching Top 250 Movies from IMDb ->", IMDB_TOP_250_MOVIES_URL)
fname = "data/top250/movies.csv"
ensure_path_directory(fname)
response = get(IMDB_TOP_250_MOVIES_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = json.loads(
soup.find("script", attrs={"type": "application/ld+json"}).text
)
file = open(fname, "w")
file.write("Rank, Movie Name, IMDb Rating, Movie Link\n\n")
file.close
file = open(fname, "a")
i = 1
for movie in json_data["itemListElement"]:
movie_rank = i
movie_name = movie["item"]["name"]
movie_rating = movie["item"]["aggregateRating"]["ratingValue"]
movie_link = movie["item"]["url"]
file.write(
f'"{movie_rank}", "{movie_name}", "{movie_rating}", "{movie_link}"\n'
)
i += 1
file.close
def fetch_popular_shows() -> list[dict]:
"""
Fetch information about popular TV Shows from IMDb.
Returns:
list of dict: A list where each dictionary contains TV Show information,
such as the TV Show's name, link, and rating.
"""
print(f"Fetching Popular TV Show {CURRENT_YEAR} from IMDb ->", IMDB_POPULAR_TV_URL)
show_data = []
response = get(IMDB_POPULAR_TV_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = json.loads(soup.find("script", type="application/ld+json").text)
for show in json_data["itemListElement"]:
show_name = show["item"]["name"]
try:
show_rating = show["item"]["aggregateRating"]["ratingValue"]
except KeyError:
show_rating = 0
show_link = show["item"]["url"]
show_data.append({"name": show_name, "rating": show_rating, "link": show_link})
return show_data
def fetch_top_50_shows() -> list[dict]:
"""
Fetch information about the Top 50 Shows of the current year from IMDb.
Returns:
list of dict: A list where each dictionary contains TV Show information,
such as the TV Show's name and link.
"""
print(f"Fetching Top 50 shows {CURRENT_YEAR} from IMDb ->", IMDB_TV_SEARCH_URL)
show_data = []
response = get(IMDB_TV_SEARCH_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = (
json.loads(soup.find("script", id="__NEXT_DATA__").text)
.get("props", {})
.get("pageProps", {})
.get("searchResults", {})
.get("titleResults", {})
.get("titleListItems")
)
for show in json_data:
show_data.append(
{
"name": show["originalTitleText"],
"link": IMDB_BASE_URL + "/title/" + show["titleId"] + "/",
"rating": show["ratingSummary"]["aggregateRating"],
}
)
return show_data
def fetch_top_250_tv():
"""
Fetch the Top 250 TV Shows from IMDb and save them to a CSV file.
"""
print(f"Fetching Top 250 TV Shows from IMDb ->", IMDB_TOP_250_TV_URL)
fname = "data/top250/shows.csv"
ensure_path_directory(fname)
response = get(IMDB_TOP_250_TV_URL, headers=HEADERS)
soup = BeautifulSoup(response.text, "html.parser")
json_data = json.loads(
soup.find("script", attrs={"type": "application/ld+json"}).text
)
file = open(fname, "w")
file.write("Rank, Show Name, IMDb Rating, Show Link\n\n")
file.close
file = open(fname, "a")
i = 1
for show in json_data["itemListElement"]:
show_rank = i
show_name = show["item"]["name"]
show_rating = show["item"]["aggregateRating"]["ratingValue"]
show_link = show["item"]["url"]
file.write(f'"{show_rank}", "{show_name}", "{show_rating}", "{show_link}"\n')
i += 1
file.close
def print_top_50_movies(movies_data):
"""
Print the Top 50 Movie names.
Args:
movies_data (list of dict): A list where each dictionary contains movie information,
such as the Movie's name and link.
"""
file = open("temp.csv", "w")
file.write("Rank; Movie Name; Movie Link\n\n")
for i, movie in enumerate(movies_data[:50], 1):
file.write(f'"{i}"; "{movie["name"]}"; "{movie["link"]}"\n')
file.close()
subprocess.call(["csvtomd", "-d", ";", "temp.csv"])
os.remove("temp.csv")
def ensure_path_directory(full_path):
"""
Function to ensure that the directory exists for any given path.
Args:
full_path (str): The full path of the directory.
"""
directory = os.path.dirname(full_path)
if not os.path.exists(directory):
os.makedirs(directory)
def save_to_csv(fetched_data, file_path, content_type):
"""
Save fetched data to a CSV file.
Args:
fetched_data (list of dict): A list where each dictionary contains Movie/Show information,
such as the Movie/Show's name and link.
file_path (str): The file path where the data should be saved.
"""
ensure_path_directory(file_path)
if content_type == "movies":
header = "Rank, Movie Name, IMDb Rating, Link"
else:
header = "Rank, Show Name, IMDb Rating, Link"
file = open(file_path, "w")
file.write(header + "\n\n")
file.close()
file = open(file_path, "a")
for i, item in enumerate(fetched_data, 1):
file.write(f'"{i}", "{item["name"]}", "{item["rating"]}", "{item["link"]}"\n')
file.close()
def save_to_md(fetched_data):
"""
Save Movie data to a Markdown file.
Args:
fetched_data (list of dict): A list where each dictionary contains Movie/Show information,
such as the Movie/Show's name and link.
"""
file = open("README.md", "w")
file.write("# IMDb Top 50 & 250 Movie/TV Show Data Scraper\n\n")
file.close()
file = open("README.md", "a")
file.write(f"## Original Medium Post: [Link]({ORIGINAL_POST_URL})\n")
file.write(f"\n**Top IMDb Movies as of:** {datetime.now().date()}\n\n")
file.write(f"**IMDb Top 50 Movies Page:** [Link]({IMDB_MOVIES_SEARCH_URL})\n\n")
file.write(f"**IMDb Top 250 Movies Page:** [Link]({IMDB_TOP_250_MOVIES_URL})\n\n")
file.write(
"**Top 50 Movies:** [CSV File](/data/top50/movies.csv), [JSON File](/data/top50/movies.json)\n\n"
)
file.write(
"**Top 250 Movies:** [CSV File](/data/top250/movies.csv), [JSON File](/data/top250/movies.json)\n\n"
)
file.write(
"**Top 50 TV Shows:** [CSV File](/data/top50/shows.csv), [JSON File](/data/top50/shows.json)\n\n"
)
file.write(
"**Top 250 TV Shows:** [CSV File](/data/top250/shows.csv), [JSON File](/data/top250/shows.json)\n\n"
)
file.write(
"**Popular Movies:** [CSV File](/data/popular/movies.csv), [JSON File](/data/popular/movies.json)\n\n"
)
file.write(
"**Popular TV Shows:** [CSV File](/data/popular/shows.csv), [JSON File](/data/popular/shows.json)\n\n"
)
file.write("---\n\n")
file.write("## IMDb Top 50 Movies List\n\n")
for i, item in enumerate(fetched_data, 1):
file.write(f"{i}. [{item["name"]}]({item["link"]})\n\n")
file.close()
if __name__ == "__main__":
print("/// IMDb Top 50 & 250 Movie/TV Show Data Scraper ///")
print("")
print(f"Original Medium Post: {ORIGINAL_POST_URL}")
print("")
fetched_movies = fetch_top_50_movies()
save_to_csv(fetched_movies, "data/top50/movies.csv", "movies")
save_to_md(fetched_movies)
fetch_top_250_movies()
fetched_shows = fetch_top_50_shows()
save_to_csv(fetched_shows, "data/top50/shows.csv", "shows")
fetch_top_250_tv()
fetched_popular_movies = fetch_popular_movies()
save_to_csv(fetched_popular_movies, "data/popular/movies.csv", "movies")
fetched_popular_shows = fetch_popular_shows()
save_to_csv(fetched_popular_shows, "data/popular/shows.csv", "shows")
if sys.version_info < (3, 10):
print_top_50_movies(movie_names, movie_links)
print("")
print(f"Original Medium Post: {ORIGINAL_POST_URL}")