-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathadd.py
2215 lines (1912 loc) · 104 KB
/
add.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
# =============================================================================
# Soluify | Your #1 IT Problem Solver | {list-sync v0.5.7}
# =============================================================================
# __ _
# (_ _ | .(_
# __)(_)||_||| \/
# /
# © 2024
# -----------------------------------------------------------------------------
import base64
import getpass
import json
import logging
import os
import sqlite3
import time
import readline
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Any
import re
import requests
from colorama import Style, init
from cryptography.fernet import Fernet
from halo import Halo
from seleniumbase import SB
from dotenv import load_dotenv
from discord_webhook import DiscordWebhook, DiscordEmbed
# Initialize colorama for cross-platform colored terminal output
init(autoreset=True)
# Define paths for config and database
DATA_DIR = "./data"
CONFIG_FILE = os.path.join(DATA_DIR, "config.enc")
DB_FILE = os.path.join(DATA_DIR, "list_sync.db")
# Load environment variables if .env exists
if os.path.exists('.env'):
load_dotenv()
class SyncResults:
def __init__(self):
self.start_time = time.time()
self.not_found_items = [] # For #1
self.error_items = [] # For #4
self.media_type_counts = {"movie": 0, "tv": 0} # For #5
self.year_distribution = {
"pre-1980": 0,
"1980-1999": 0,
"2000-2019": 0,
"2020+": 0
} # For #8
self.total_items = 0
self.results = {
"requested": 0,
"already_requested": 0,
"already_available": 0,
"not_found": 0,
"error": 0,
"skipped": 0
}
def custom_input(prompt):
readline.set_startup_hook(lambda: readline.insert_text(''))
try:
return input(prompt)
finally:
readline.set_startup_hook()
def ensure_data_directory_exists():
os.makedirs(DATA_DIR, exist_ok=True)
def setup_logging():
# Create a formatter
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
# Set up file handler for general logging (DEBUG and above)
file_handler = logging.FileHandler(os.path.join(DATA_DIR, "list_sync.log"), encoding='utf-8')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
# Create a custom filter to block non-colored output
class ColoredOutputFilter(logging.Filter):
def filter(self, record):
# Only allow ERROR level messages that are explicitly marked for console
return False # Block all logging to console
# Set up console handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.ERROR)
console_handler.setFormatter(formatter)
console_handler.addFilter(ColoredOutputFilter())
# Set up the root logger
root_logger = logging.getLogger()
root_logger.setLevel(logging.DEBUG) # Capture all levels
# Remove any existing handlers
for handler in root_logger.handlers[:]:
root_logger.removeHandler(handler)
# Add our handlers
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
# Set up separate logger for added items
added_logger = logging.getLogger("added_items")
added_logger.setLevel(logging.INFO)
added_handler = logging.FileHandler(os.path.join(DATA_DIR, "added.log"))
added_handler.setFormatter(logging.Formatter("%(asctime)s - %(message)s"))
added_logger.addHandler(added_handler)
# Prevent added_logger from propagating to root logger
added_logger.propagate = False
selenium_logger = logging.getLogger('selenium')
selenium_logger.setLevel(logging.INFO)
selenium_logger.propagate = False
# Disable urllib3 logging to console
urllib3_logger = logging.getLogger('urllib3')
urllib3_logger.setLevel(logging.INFO)
urllib3_logger.propagate = False
return added_logger
def init_database():
with sqlite3.connect(DB_FILE) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS lists (
id INTEGER PRIMARY KEY AUTOINCREMENT,
list_type TEXT NOT NULL,
list_id TEXT NOT NULL,
UNIQUE(list_type, list_id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS synced_items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
media_type TEXT NOT NULL,
imdb_id TEXT,
overseerr_id INTEGER,
status TEXT,
last_synced TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS sync_interval (
id INTEGER PRIMARY KEY AUTOINCREMENT,
interval_hours INTEGER NOT NULL
)
''')
conn.commit()
def color_gradient(text, start_color, end_color):
def hex_to_rgb(hex_code):
return tuple(int(hex_code[i : i + 2], 16) for i in (0, 2, 4))
start_rgb = hex_to_rgb(start_color.lstrip("#"))
end_rgb = hex_to_rgb(end_color.lstrip("#"))
gradient_text = ""
steps = len(text)
for i, char in enumerate(text):
ratio = i / steps
r = int(start_rgb[0] + (end_rgb[0] - start_rgb[0]) * ratio)
g = int(start_rgb[1] + (end_rgb[1] - start_rgb[1]) * ratio)
b = int(start_rgb[2] + (end_rgb[2] - start_rgb[2]) * ratio)
gradient_text += f"\033[38;2;{r};{g};{b}m{char}"
return gradient_text + Style.RESET_ALL
def display_ascii_art():
ascii_art = r"""
_ _ _ ___
| | (_) ___ | |_ / __| _ _ _ _ __
| |__ | | (_-< | _| \__ \ | || | | ' \ / _|
|____| |_| /__/ \__| |___/ \_, | |_||_| \__|
|__/
"""
art_lines = ascii_art.split("\n")
for line in art_lines:
print(color_gradient(line, "#00aaff", "#00ffaa"))
time.sleep(0.1)
print(Style.RESET_ALL)
def display_banner():
"""Display the banner."""
banner = """
==============================================================
Soluify - {servarr-tools_list-sync_v0.5.7}
==============================================================
"""
print(color_gradient(banner, "#00aaff", "#00ffaa"))
def encrypt_config(data, password):
key = base64.urlsafe_b64encode(password.encode().ljust(32)[:32])
fernet = Fernet(key)
return fernet.encrypt(json.dumps(data).encode())
def decrypt_config(encrypted_data, password):
key = base64.urlsafe_b64encode(password.encode().ljust(32)[:32])
fernet = Fernet(key)
return json.loads(fernet.decrypt(encrypted_data).decode())
def save_config(overseerr_url, api_key, requester_user_id):
config = {"overseerr_url": overseerr_url, "api_key": api_key, "requester_user_id": requester_user_id}
print(color_gradient("🔐 Enter a password to encrypt your API details: ", "#ff0000", "#aa0000"), end="")
password = getpass.getpass("")
encrypted_config = encrypt_config(config, password)
with open(CONFIG_FILE, "wb") as f:
f.write(encrypted_config)
print(f'\n{color_gradient("✅ Details encrypted. Remember your password!", "#00ff00", "#00aa00")}\n')
def load_config():
if os.path.exists(CONFIG_FILE):
with open(CONFIG_FILE, "rb") as f:
encrypted_config = f.read()
max_attempts = 3
current_attempt = 0
while current_attempt < max_attempts:
print() # Ensure password prompt is on a new line
password = getpass.getpass(color_gradient("🔑 Enter your password: ", "#ff0000", "#aa0000"))
try:
config = decrypt_config(encrypted_config, password)
print() # Add a newline after successful password entry
return config["overseerr_url"], config["api_key"], config["requester_user_id"]
except Exception:
current_attempt += 1
if current_attempt < max_attempts:
print(color_gradient("\n❌ Incorrect password. Please try again.", "#ff0000", "#aa0000"))
else:
print(color_gradient("\n❌ Maximum password attempts reached.", "#ff0000", "#aa0000"))
if custom_input("\n🗑️ Delete this config and start over? (y/n): ").lower() == "y":
os.remove(CONFIG_FILE)
print(color_gradient("\n🔄 Config deleted. Rerun the script to set it up again.", "#ffaa00", "#ff5500") + "\n")
return None, None, None
return None, None, None
def test_overseerr_api(overseerr_url, api_key):
headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
test_url = f"{overseerr_url}/api/v1/status"
spinner = Halo(text=color_gradient("🔍 Testing API connection...", "#ffaa00", "#ff5500"), spinner="dots")
spinner.start()
try:
response = requests.get(test_url, headers=headers)
response.raise_for_status()
spinner.succeed(color_gradient("🎉 API connection successful!", "#00ff00", "#00aa00"))
logging.info("Overseerr API connection successful!")
except Exception as e:
spinner.fail(color_gradient(f"❌ Overseerr API connection failed. Error: {str(e)}", "#ff0000", "#aa0000"))
logging.error(f"Overseerr API connection failed. Error: {str(e)}")
raise
def set_requester_user(overseerr_url, api_key):
headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
users_url = f"{overseerr_url}/api/v1/user"
try:
requester_user_id = "1"
response = requests.get(users_url, headers=headers)
response.raise_for_status()
jsonResult = response.json()
if jsonResult['pageInfo']['results'] > 1:
print(color_gradient("\n📋 Multiple users detected, you can choose which user will make the requests on ListSync behalf.\n", "#00aaff", "#00ffaa"))
for result in jsonResult['results']:
print(color_gradient(f"{result['id']}. {result['displayName']}", "#ffaa00", "#ff5500"))
requester_user_id = custom_input(color_gradient("\nEnter the number of the list to use as requester user: ", "#ffaa00", "#ff5500"))
if not next((x for x in jsonResult['results'] if str(x['id']) == requester_user_id), None):
requester_user_id = "1"
print(color_gradient("\n❌ Invalid option, using admin as requester user.", "#ff0000", "#aa0000"))
logging.info("Requester user set!")
return requester_user_id
except Exception as e:
logging.error(f"Overseerr API connection failed. Error: {str(e)}")
return 1
def fetch_imdb_list(list_id):
"""Fetch IMDb list using Selenium with pagination"""
media_items = []
print(color_gradient("📚 Fetching IMDB list...", "#ffaa00", "#ff5500"))
try:
with SB(uc=True, headless=True) as sb:
# Handle full URLs vs list IDs
if list_id.startswith(('http://', 'https://')):
url = list_id.rstrip('/') # Use the provided URL directly
if '/chart/' in url:
is_chart = True
elif '/list/' in url or '/user/' in url:
is_chart = False
else:
raise ValueError("Invalid IMDb URL format")
else:
# Existing logic for list IDs
if list_id in ['top', 'boxoffice', 'moviemeter', 'tvmeter']:
url = f"https://www.imdb.com/chart/{list_id}"
is_chart = True
elif list_id.startswith("ls"):
url = f"https://www.imdb.com/list/{list_id}"
is_chart = False
elif list_id.startswith("ur"):
url = f"https://www.imdb.com/user/{list_id}/watchlist"
is_chart = False
else:
raise ValueError("Invalid IMDb list ID format")
logging.info(f"Attempting to load URL: {url}")
sb.open(url)
# Common wait logic for all IMDb pages (both lists and charts)
logging.info(f"Attempting to load IMDb page: {url}")
sb.open(url)
# Initial wait for page load
sb.sleep(5) # Longer initial wait to ensure page starts loading
# Add some human-like scrolling behavior to avoid bot detection
try:
sb.execute_script("window.scrollTo(0, 300);")
sb.sleep(1)
sb.execute_script("window.scrollTo(0, 600);")
sb.sleep(1)
except Exception as e:
logging.warning(f"Could not perform scrolling: {str(e)}")
# Wait for any potential captcha/anti-bot verification to load
sb.sleep(3)
if is_chart:
# Wait for chart content to load with multiple fallback selectors
chart_found = False
# Try different approaches to find chart content
# First, try direct data-testid selectors
data_testid_selectors = [
'[data-testid="chart-layout-parent"]',
'[data-testid="chart-layout-main-column"]',
'[data-testid="chart-layout-total-items"]'
]
for selector in data_testid_selectors:
try:
logging.info(f"Trying to find chart with data-testid selector: {selector}")
# Use a longer timeout for charts
sb.wait_for_element_present(selector, timeout=10)
chart_found = True
logging.info(f"Chart parent found with selector: {selector}")
# Add extra wait after finding the element to ensure it's fully loaded
sb.sleep(2)
break
except Exception as e:
logging.warning(f"Could not find chart with data-testid selector {selector}: {str(e)}")
# If not found, try different class-based selectors for the list itself
if not chart_found:
class_selectors = [
'ul.ipc-metadata-list.compact-list-view',
'ul.ipc-metadata-list.detailed-list-view',
'.ipc-metadata-list.ipc-metadata-list--dividers-between',
'ul.ipc-metadata-list' # Most generic one
]
for selector in class_selectors:
try:
logging.info(f"Trying to find chart with class selector: {selector}")
# Use a longer timeout for charts
sb.wait_for_element_present(selector, timeout=10)
chart_found = True
logging.info(f"Chart found with selector: {selector}")
# Add extra wait after finding the element
sb.sleep(2)
break
except Exception as e:
logging.warning(f"Could not find chart with class selector {selector}: {str(e)}")
if not chart_found:
# Try a more aggressive approach with longer waits and more scrolling
logging.warning("Could not find chart with standard selectors, trying more aggressive approach")
sb.sleep(8) # Wait longer for full page load
# Add more extensive human-like behavior
sb.execute_script("window.scrollTo(0, 300);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 600);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 900);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 1200);")
sb.sleep(2)
# Scroll back up a bit to simulate natural browsing
sb.execute_script("window.scrollTo(0, 800);")
sb.sleep(3)
# Try a very generic selector that should match any list with a much longer timeout
try:
sb.wait_for_element_present('ul', timeout=15)
# If we find any ul, let's look for list items inside it
uls = sb.find_elements('ul')
for ul in uls:
try:
items = ul.find_elements("css selector", "li")
if len(items) > 5: # If we find a list with several items, it's likely our chart
logging.info(f"Found a ul with {len(items)} items, likely our chart")
chart_found = True
break
except Exception:
pass
except Exception as e:
logging.error(f"Could not find any ul elements after scrolling: {str(e)}")
if not chart_found:
raise ValueError("Could not find chart content on IMDb page after multiple attempts")
# Get total number of items if possible
try:
total_elements = sb.find_elements('[data-testid="chart-layout-total-items"]')
if total_elements:
total_text = total_elements[0].text
total_match = re.search(r'(\d+)\s+Titles?', total_text)
if total_match:
total_items = int(total_match.group(1))
logging.info(f"Total items in chart: {total_items}")
else:
total_items = None
except Exception as e:
logging.warning(f"Could not determine total items: {str(e)}")
total_items = None
# Process items in the chart - try multiple selectors for items
items = []
# Try different selectors for the chart items, starting with the most specific
item_selectors = [
"li.ipc-metadata-list-summary-item", # Most specific for compact view
".ipc-metadata-list-summary-item", # Alternative for compact view
".cli-parent", # From the example
".ipc-metadata-list-item" # For other views
]
for selector in item_selectors:
try:
logging.info(f"Trying to find list items with selector: {selector}")
items = sb.find_elements(selector)
if items and len(items) > 0:
logging.info(f"Found {len(items)} items using selector: {selector}")
break
except Exception as e:
logging.warning(f"Could not find items with selector {selector}: {str(e)}")
if not items or len(items) == 0:
# Last resort: try to find any list items on the page
try:
items = sb.find_elements("li")
logging.warning(f"Using generic li selector as fallback, found {len(items)} items")
except Exception as e:
logging.error(f"Could not find any list items on the page: {str(e)}")
raise ValueError("Could not find any list items in the chart")
logging.info(f"Found {len(items)} items in chart")
for item in items:
try:
# Get title element - try multiple selectors
title_element = None
full_title = ""
title_selectors = [
".ipc-title__text",
"h3.ipc-title__text",
".cli-title h3",
"a.ipc-title-link-wrapper"
]
for selector in title_selectors:
try:
title_elements = item.find_elements("css selector", selector)
if title_elements:
for element in title_elements:
element_text = element.text
if element_text and len(element_text) > 0:
full_title = element_text
logging.info(f"Found title using selector: {selector}")
break
if full_title:
break
except Exception:
pass
if not full_title:
# Last resort: try to get any text from the item
try:
item_text = item.text
text_lines = item_text.split("\n")
for line in text_lines:
if line and len(line) > 2 and not line.isdigit() and not re.match(r'^\d+\.$', line):
full_title = line
logging.warning(f"Using fallback method for title: {full_title}")
break
except Exception:
pass
if not full_title:
logging.warning("Could not find title for item, skipping")
continue
# Remove ranking number if present (e.g., "1. The Shawshank Redemption" -> "The Shawshank Redemption")
title = re.sub(r'^\d+\.\s*', '', full_title)
# Get year from metadata with various selectors
year = None
metadata_text = ""
metadata_selectors = [
".cli-title-metadata",
".cli-title-metadata-item",
".sc-44e0e03-6",
".sc-44e0e03-7"
]
for selector in metadata_selectors:
try:
metadata_elements = item.find_elements("css selector", selector)
if metadata_elements:
for element in metadata_elements:
element_text = element.text
metadata_text += " " + element_text
# Try to extract year directly from this element
year_match = re.search(r'(\d{4})', element_text)
if year_match:
year = int(year_match.group(1))
break
if year:
break
except Exception:
pass
if not year and metadata_text:
# Try to extract year from concatenated metadata
year_match = re.search(r'(\d{4})', metadata_text)
if year_match:
year = int(year_match.group(1))
# If still no year, try to extract from the item's entire text
if not year:
try:
item_text = item.text
year_match = re.search(r'(\d{4})', item_text)
if year_match:
year = int(year_match.group(1))
except Exception:
pass
# Get IMDB ID from the title link - try different approaches
imdb_id = None
link_selectors = [
"a.ipc-title-link-wrapper",
"a[href*='/title/']",
"a" # Most generic selector
]
for selector in link_selectors:
try:
links = item.find_elements("css selector", selector)
for link in links:
href = link.get_attribute("href")
if href and "/title/" in href:
# Extract IMDb ID from URL
imdb_match = re.search(r'/title/(tt\d+)', href)
if imdb_match:
imdb_id = imdb_match.group(1)
break
if imdb_id:
break
except Exception:
pass
if not imdb_id:
logging.warning(f"Could not find IMDb ID for {title}, skipping")
continue
# For charts, all items are movies unless explicitly marked as TV
media_type = "movie"
if metadata_text and ("TV" in metadata_text or "Series" in metadata_text):
media_type = "tv"
media_items.append({
"title": title.strip(),
"imdb_id": imdb_id,
"media_type": media_type,
"year": year
})
logging.info(f"Added {media_type}: {title} ({year}) (IMDB ID: {imdb_id})")
except Exception as e:
logging.warning(f"Failed to parse IMDb chart item: {str(e)}")
continue
else:
# For regular lists
try:
# Wait for list content to load with a more resilient approach
logging.info("Waiting for list content to load...")
# Try multiple selector approaches in sequence with longer timeouts
content_found = False
# First try the data-testid attribute
try:
logging.info("Looking for content by data-testid attribute...")
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
content_found = True
logging.info("Found content by data-testid attribute")
# Add extra wait after finding the element
sb.sleep(2)
except Exception as e:
logging.warning(f"Could not find content by data-testid: {str(e)}")
# If that fails, try looking for the list element directly
if not content_found:
try:
logging.info("Looking for list element directly...")
sb.wait_for_element_present("ul.ipc-metadata-list", timeout=10)
content_found = True
logging.info("Found list element directly")
# Add extra wait after finding the element
sb.sleep(2)
except Exception as e:
logging.warning(f"Could not find list element: {str(e)}")
# If that also fails, try looking for list items
if not content_found:
try:
logging.info("Looking for list items...")
sb.wait_for_element_present("li.ipc-metadata-list-summary-item", timeout=10)
content_found = True
logging.info("Found list items")
# Add extra wait after finding the element
sb.sleep(2)
except Exception as e:
logging.warning(f"Could not find list items: {str(e)}")
# If everything fails, try a more aggressive approach with longer waits and scrolling
if not content_found:
logging.warning("Could not find list content, attempting more aggressive approach...")
# Scroll more and wait longer
sb.sleep(8)
# Add more extensive human-like behavior
sb.execute_script("window.scrollTo(0, 300);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 600);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 900);")
sb.sleep(2)
sb.execute_script("window.scrollTo(0, 1200);")
sb.sleep(2)
# Scroll back up a bit to simulate natural browsing
sb.execute_script("window.scrollTo(0, 800);")
sb.sleep(3)
# Reload the page to handle potential temporary glitches
sb.open(url)
sb.sleep(10) # Wait longer after reload
# Try once more with very generic selectors and longer timeouts
try:
# Try to find any ul element with items
sb.wait_for_element_present("ul", timeout=15)
uls = sb.find_elements("ul")
for ul in uls:
try:
items = ul.find_elements("css selector", "li")
if len(items) > 5: # If we find a list with several items, it's likely our list
logging.info(f"Found a ul with {len(items)} items, likely our list content")
content_found = True
break
except Exception:
pass
if not content_found:
raise ValueError("Could not find list content on IMDb page after multiple attempts")
except Exception as e:
logging.error(f"Could not find any list content after multiple attempts: {str(e)}")
raise ValueError("Could not find list content on IMDb page after multiple attempts")
# Additional wait to ensure everything is loaded
sb.sleep(3)
except Exception as e:
logging.error(f"Failed to load IMDb list page: {str(e)}")
raise
# Get total number of items
try:
# Try to find the container with the total items count using exact classes from HTML
titles_container = sb.find_element("css selector", ".ipc-inline-list__item.sc-d6269c7a-1")
if titles_container:
total_text = titles_container.text
# Extract the number from text like "500 titles"
titles_match = re.search(r'(\d+)\s*titles?', total_text, re.IGNORECASE)
if titles_match:
total_items = int(titles_match.group(1))
logging.info(f"Total items in list: {total_items}")
expected_pages = (total_items + 249) // 250 # Round up division by 250
logging.info(f"Expected number of pages: {expected_pages}")
else:
# Try another approach - find the text showing range like "1 - 250"
range_container = sb.find_element("css selector", ".ipc-inline-list__item")
range_text = range_container.text
logging.info(f"Found range text: {range_text}")
if " - " in range_text:
# This is like "1 - 250"
try:
_, end = range_text.split(" - ")
per_page = int(end)
logging.info(f"Items per page: {per_page}")
# Find total in the next element
next_item = sb.find_element("css selector", ".ipc-inline-list__item.sc-d6269c7a-1")
if next_item:
titles_text = next_item.text
titles_match = re.search(r'(\d+)', titles_text)
if titles_match:
total_items = int(titles_match.group(1))
expected_pages = (total_items + per_page - 1) // per_page
logging.info(f"Total items: {total_items}, expected pages: {expected_pages}")
except Exception as e:
logging.warning(f"Could not parse range: {str(e)}")
total_items = None
expected_pages = None
else:
total_items = None
expected_pages = None
else:
logging.warning("Total items container not found")
total_items = None
expected_pages = None
except Exception as e:
logging.warning(f"Could not determine total items using new selector: {str(e)}")
# Fallback to original selector
try:
total_element = sb.find_element('[data-testid="list-page-mc-total-items"]')
total_text = total_element.text
total_items = int(re.search(r'(\d+)\s+titles?', total_text).group(1))
logging.info(f"Total items in list (fallback): {total_items}")
expected_pages = (total_items + 249) // 250 # Round up division by 250
except Exception as e2:
logging.warning(f"Could not determine total items with fallback: {str(e2)}")
total_items = None
expected_pages = None
current_page = 1
# Process items on the page
while True:
# Try multiple approaches to find list items
items = []
# First try using the most specific selector
try:
items = sb.find_elements("css selector", "li.ipc-metadata-list-summary-item")
if items:
logging.info(f"Found {len(items)} items using specific selector")
except Exception as e:
logging.warning(f"Could not find items using specific selector: {str(e)}")
# If that fails, try a more generic selector
if not items:
try:
items = sb.find_elements("css selector", ".ipc-metadata-list-summary-item")
if items:
logging.info(f"Found {len(items)} items using generic class selector")
except Exception as e:
logging.warning(f"Could not find items using generic selector: {str(e)}")
# If that also fails, try an even more generic approach
if not items:
try:
# Try to find the list first
list_element = sb.find_element("css selector", "ul.ipc-metadata-list")
# Then get its children
items = list_element.find_elements("css selector", "li")
if items:
logging.info(f"Found {len(items)} items via parent list element")
except Exception as e:
logging.warning(f"Could not find items via parent: {str(e)}")
logging.info(f"Processing page {current_page}: Found {len(items)} items")
if not items:
logging.warning("No items found on this page, attempting to continue to next page")
# We might need to try the next page
if current_page < (expected_pages or 2): # Try at least page 2 if we don't know expected pages
# Try to navigate to next page directly
next_page = current_page + 1
next_url = f"{url}/?page={next_page}"
logging.info(f"Attempting to navigate directly to page {next_page}: {next_url}")
sb.open(next_url)
sb.sleep(5) # Wait longer for page load
current_page += 1
continue
else:
logging.info("No more pages expected, breaking loop")
break
for item in items:
try:
# Get title element with multiple fallbacks
title_element = None
full_title = ""
# Try different approaches to find the title
selectors_to_try = [
".ipc-title__text",
"h3.ipc-title__text",
"a.ipc-title-link-wrapper h3",
".dli-title h3"
]
for selector in selectors_to_try:
try:
title_element = item.find_element("css selector", selector)
if title_element:
full_title = title_element.text
logging.info(f"Found title using selector: {selector}")
break
except Exception:
pass
if not full_title:
# Last resort: try to get any text from the item
full_title = item.text.split("\n")[0]
logging.warning(f"Using fallback method for title: {full_title}")
title = re.sub(r'^\d+\.\s*', '', full_title) # Remove the numbering (e.g., "1. ")
# Get year from metadata with multiple fallbacks
year = None
metadata_text = ""
# Try different approaches to find the metadata
metadata_selectors = [
".sc-44e0e03-6.liNdun",
".dli-title-metadata",
".sc-44e0e03-6",
"[class*='title-metadata']"
]
for selector in metadata_selectors:
try:
metadata = item.find_element("css selector", selector)
if metadata:
metadata_text = metadata.text
logging.info(f"Found metadata using selector: {selector}")
break
except Exception:
pass
# Extract year if we found metadata text
if metadata_text:
# Extract year from formats like "2008–2013" or "2024"
year_match = re.search(r'(\d{4})', metadata_text)
if year_match:
year = int(year_match.group(1))
logging.debug(f"Extracted year for {title}: {year}")
# More robust media type detection
media_type = "movie" # default
if metadata_text:
# Look for TV Series indicator in metadata text
if "TV Series" in metadata_text or "TV Mini Series" in metadata_text:
media_type = "tv"
# Or try to find episodes indicator
elif "eps" in metadata_text.lower() or "episodes" in metadata_text.lower():
media_type = "tv"
# Get IMDB ID from the title link with multiple fallbacks
imdb_id = None
link_selectors = [
"a.ipc-title-link-wrapper",
"a[href*='/title/']",
".dli-title a"
]
for selector in link_selectors:
try:
title_link = item.find_element("css selector", selector)
if title_link:
href = title_link.get_attribute("href")
if href and "/title/" in href:
imdb_id = href.split("/")[4]
logging.info(f"Found IMDb ID using selector: {selector}")
break
except Exception:
pass
if not imdb_id:
# Try to extract it from any href in the item
try:
links = item.find_elements("css selector", "a")
for link in links:
href = link.get_attribute("href")
if href and "/title/" in href:
imdb_id = href.split("/")[4]
logging.info("Found IMDb ID from generic link")
break
except Exception:
pass
if not imdb_id:
logging.warning(f"Could not find IMDb ID for {title}, skipping")
continue
media_items.append({
"title": title.strip(),
"imdb_id": imdb_id,
"media_type": media_type,
"year": year
})
logging.info(f"Added {media_type}: {title} ({year}) (IMDB ID: {imdb_id})")
except Exception as e:
logging.warning(f"Failed to parse IMDb item: {str(e)}")
continue
# Check if we've processed all expected pages
if expected_pages and current_page >= expected_pages:
logging.info(f"Reached final page {current_page} of {expected_pages}")
break
# Try to navigate to next page
try:
# First try clicking the button using a more specific selector
try:
# Log the HTML structure to help debugging
logging.info("Looking for next button...")
pagination_element = sb.find_element("css selector", "div[data-testid='index-pagination']")
if pagination_element:
logging.info("Pagination element found")
next_button = sb.find_element(
"css selector",
"button[data-testid='index-pagination-nxt']"
)
# Check if the button is disabled
if next_button:
is_disabled = next_button.get_attribute("disabled")
logging.info(f"Next button found, disabled attribute: {is_disabled}")
if is_disabled:
logging.info("Next button is disabled, no more pages")
break
# Button is enabled, so click it
sb.execute_script("arguments[0].scrollIntoView(true);", next_button)
sb.sleep(1) # Give time for scrolling
next_button.click()
# Wait for loading spinner to disappear and content to load
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3) # Additional wait for content to fully render
# Verify we have items on the page
new_items = sb.find_elements("css selector", "li.ipc-metadata-list-summary-item")
if not new_items:
logging.warning(f"No items found after navigation to page {current_page + 1}, retrying...")
# Fall back to direct URL navigation
next_page = current_page + 1
next_url = f"{url}/?page={next_page}"
sb.open(next_url)
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3)
except Exception as e:
logging.info(f"Could not click next button: {str(e)}")
# Fall back to direct URL navigation
next_page = current_page + 1
next_url = f"{url}/?page={next_page}"
logging.info(f"Attempting to navigate directly to page {next_page}: {next_url}")
sb.open(next_url)
sb.wait_for_element_present('[data-testid="list-page-mc-list-content"]', timeout=10)
sb.sleep(3)
current_page += 1
sb.sleep(2)
except Exception as e:
logging.info(f"No more pages available: {str(e)}")
break
# Validate total items found
if total_items and len(media_items) < total_items:
logging.warning(f"Only found {len(media_items)} items out of {total_items} total")
print(color_gradient(f"✨ Found {len(media_items)} items from IMDB list {list_id}!", "#00ff00", "#00aa00"))
logging.info(f"IMDB list {list_id} fetched successfully. Found {len(media_items)} items.")
return media_items