-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
834 lines (716 loc) · 37 KB
/
Copy pathmain.py
File metadata and controls
834 lines (716 loc) · 37 KB
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
import os
import time
import random
import json
import undetected_chromedriver as uc
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import tkinter as tk
from tkinter import ttk, messagebox
import threading
# === Project setup ===
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PROFILE_DIR = os.path.join(BASE_DIR, "chrome_profile") # persistent user data
URL = "https://www.topps.com/"
def create_driver():
"""Create Chrome driver using a persistent local profile"""
os.makedirs(PROFILE_DIR, exist_ok=True)
options = uc.ChromeOptions()
options.add_argument(f"--user-data-dir={PROFILE_DIR}")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("--start-maximized")
# Removing remote debugging port as it can sometimes cause hangs in uc
# options.add_argument("--remote-debugging-port=9222")
options.page_load_strategy = 'normal' # Switch back to normal to be safer
# Use headless=False explicitly for visibility
# Forcing version_main=146 to match the user's browser version as per error log
driver = uc.Chrome(options=options, headless=False, use_subprocess=True, version_main=146)
driver.set_page_load_timeout(60) # Longer timeout
return driver
def close_topps_popups(driver):
"""Attempt to close common Topps popups like cookie consent or email signups"""
try:
selectors = [
"#onetrust-accept-btn-handler",
".onetrust-close-btn-handler",
"button[aria-label='Close']",
".kl-private-reset-css-p9660t button",
"button[id*='close']",
"div[class*='close']"
]
for sel in selectors:
try:
elements = driver.find_elements(By.CSS_SELECTOR, sel)
for el in elements:
if el.is_displayed():
el.click()
except:
pass
except:
pass
def human_type(element, text, min_delay=0.05, max_delay=0.18, pause_after=0.02, driver=None):
"""
Types `text` into `element` one character at a time with random delays.
"""
try:
element.clear()
for ch in text:
element.send_keys(ch)
time.sleep(random.uniform(min_delay, max_delay))
time.sleep(pause_after)
except Exception:
if driver:
driver.execute_script("arguments[0].value = arguments[1];", element, text)
driver.execute_script("arguments[0].dispatchEvent(new Event('input', { bubbles: true }));", element)
def contactFormFill(driver):
try:
close_topps_popups(driver)
# Load contact info from config.json
config_path = os.path.join(BASE_DIR, "config.json")
with open(config_path, 'r') as f:
config = json.load(f)
contact_info = config["contact_info"]
payment_info = config["payment_info"]
wait = WebDriverWait(driver, 10)
# First name - using ID TextField0
firstName = wait.until(EC.element_to_be_clickable((By.ID, "TextField0")))
driver.execute_script("arguments[0].scrollIntoView(true);", firstName)
human_type(firstName, contact_info["firstName"], driver=driver)
# Last name - using ID TextField1
lastName = wait.until(EC.element_to_be_clickable((By.ID, "TextField1")))
human_type(lastName, contact_info["lastName"], driver=driver)
# Address - using ID shipping-address1
address = wait.until(EC.element_to_be_clickable((By.ID, "shipping-address1")))
human_type(address, contact_info["address"], driver=driver)
# City - using ID TextField3
city = wait.until(EC.element_to_be_clickable((By.ID, "TextField3")))
human_type(city, contact_info["city"], driver=driver)
# Select state from dropdown - using ID Select1
state_dropdown = wait.until(EC.element_to_be_clickable((By.ID, "Select1")))
from selenium.webdriver.support.ui import Select
state_select = Select(state_dropdown)
state_select.select_by_value(contact_info["state"])
# ZIP code - using ID TextField4
zipCode = wait.until(EC.element_to_be_clickable((By.ID, "TextField4")))
human_type(zipCode, contact_info["zipCode"], driver=driver)
# Phone - using ID TextField5
phone = wait.until(EC.element_to_be_clickable((By.ID, "TextField5")))
human_type(phone, contact_info["phone"], driver=driver)
# Fill payment information
# Scroll to payment section and wait
driver.execute_script("window.scrollTo(0, document.body.scrollHeight/2);")
time.sleep(random.uniform(2, 4))
# Fill payment fields
fill_payment_info(driver, payment_info)
time.sleep(random.uniform(2, 4))
except Exception as e:
print(f"Error in contactFormFill: {e}")
pass
def find_payment_iframe(driver, wait, field_type):
"""Helper function to find payment iframes by field type"""
iframe_selectors = [
f"iframe[src*='{field_type}']",
f"iframe[title*='{field_type.replace('_', ' ').title()}']",
f"iframe[id*='{field_type}']",
f"iframe.card-fields-iframe[src*='{field_type}']",
f"iframe[class*='card-fields-iframe'][src*='{field_type}']"
]
# Add specific selectors for each field type
if field_type == "number":
iframe_selectors.extend([
"iframe[title*='Card number']",
"iframe[src*='number-ltr.html']"
])
elif field_type == "expiry":
iframe_selectors.extend([
"iframe[title*='Expiration date']",
"iframe[src*='expiry-ltr.html']"
])
elif field_type == "verification_value":
iframe_selectors.extend([
"iframe[title*='Security code']",
"iframe[src*='verification_value-ltr.html']"
])
elif field_type == "name":
iframe_selectors.extend([
"iframe[title*='Name on card']",
"iframe[src*='name-ltr.html']"
])
for selector in iframe_selectors:
try:
iframe = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
return iframe
except:
continue
return None
def fill_payment_info(driver, payment_info):
"""Fill payment information in the checkout form"""
try:
wait = WebDriverWait(driver, 15)
# Scroll to payment section to ensure it's visible
driver.execute_script("window.scrollTo(0, document.body.scrollHeight/2);")
time.sleep(random.uniform(2, 3))
# Fill name on card field (now also in iframe)
try:
name_iframe = find_payment_iframe(driver, wait, "name")
if name_iframe:
driver.switch_to.frame(name_iframe)
time.sleep(random.uniform(0.5, 1))
# Try multiple approaches to fill the name on card
try:
# Approach 1: Direct interaction
name_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#number")))
name_input.click()
time.sleep(random.uniform(0.3, 0.5))
name_input.clear()
human_type(name_input, payment_info["nameOnCard"])
except:
# Approach 2: JavaScript execution
try:
driver.execute_script("""
var input = document.querySelector('input');
if (input) {
input.focus();
input.value = arguments[0];
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
""", payment_info["nameOnCard"])
except:
pass
driver.switch_to.default_content()
time.sleep(random.uniform(0.5, 1))
print("✅ Name on card filled successfully")
else:
print("❌ Could not find name on card iframe")
except Exception as e:
print(f"❌ Error filling name on card: {e}")
driver.switch_to.default_content()
# Fill card number (in iframe) - using dynamic iframe finding
try:
card_number_iframe = find_payment_iframe(driver, wait, "number")
if card_number_iframe:
driver.switch_to.frame(card_number_iframe)
time.sleep(random.uniform(0.5, 1))
# Try multiple approaches to fill the card number
try:
# Approach 1: Direct interaction
card_number_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#verification_value")))
card_number_input.click()
time.sleep(random.uniform(0.3, 0.5))
card_number_input.clear()
human_type(card_number_input, payment_info["cardNumber"])
except:
# Approach 2: JavaScript execution
try:
driver.execute_script("""
var input = document.querySelector('input');
if (input) {
input.focus();
input.value = arguments[0];
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
""", payment_info["cardNumber"])
except:
pass
driver.switch_to.default_content()
time.sleep(random.uniform(0.5, 1))
print("✅ Card number filled successfully")
else:
print("❌ Could not find card number iframe")
except Exception as e:
print(f"❌ Error filling card number: {e}")
driver.switch_to.default_content()
# Fill expiry date (in iframe) - using dynamic iframe finding
try:
expiry_iframe = find_payment_iframe(driver, wait, "expiry")
if expiry_iframe:
driver.switch_to.frame(expiry_iframe)
time.sleep(random.uniform(0.5, 1))
# Try multiple approaches to fill the expiry date
try:
# Approach 1: Direct interaction
expiry_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#expiry")))
expiry_input.click()
time.sleep(random.uniform(0.3, 0.5))
expiry_input.clear()
human_type(expiry_input, payment_info["expiryDate"])
except:
# Approach 2: JavaScript execution
try:
driver.execute_script("""
var input = document.querySelector('input');
if (input) {
input.focus();
input.value = arguments[0];
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
""", payment_info["expiryDate"])
except:
pass
driver.switch_to.default_content()
time.sleep(random.uniform(0.5, 1))
print("✅ Expiry date filled successfully")
else:
print("❌ Could not find expiry iframe")
except Exception as e:
print(f"❌ Error filling expiry date: {e}")
driver.switch_to.default_content()
# Fill security code/CVV (in iframe) - using dynamic iframe finding
try:
cvv_iframe = find_payment_iframe(driver, wait, "verification_value")
if cvv_iframe:
driver.switch_to.frame(cvv_iframe)
time.sleep(random.uniform(0.5, 1))
# Try multiple approaches to fill the security code
try:
# Approach 1: Direct interaction
cvv_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'input[placeholder="Security code"]')))
cvv_input.click()
time.sleep(random.uniform(0.3, 0.5))
cvv_input.clear()
human_type(cvv_input, payment_info["securityCode"])
except:
# Approach 2: JavaScript execution
try:
driver.execute_script("""
var input = document.querySelector('input');
if (input) {
input.focus();
input.value = arguments[0];
input.dispatchEvent(new Event('input', { bubbles: true }));
input.dispatchEvent(new Event('change', { bubbles: true }));
}
""", payment_info["securityCode"])
except:
pass
driver.switch_to.default_content()
time.sleep(random.uniform(0.5, 1))
print("✅ Security code filled successfully")
else:
print("❌ Could not find CVV iframe")
except Exception as e:
print(f"❌ Error filling security code: {e}")
driver.switch_to.default_content()
# Fill phone number in the "Remember me" section if present
try:
phone_field = wait.until(EC.element_to_be_clickable((By.ID, "TextField8")))
phone_field.click()
time.sleep(random.uniform(0.3, 0.5))
phone_field.clear()
human_type(phone_field, payment_info.get("phone", "1234567890"))
time.sleep(random.uniform(0.5, 1))
print("✅ Phone number filled successfully")
except Exception as e:
print(f"⚠️ Phone number field not found or error: {e}")
print("🎉 Payment information filled successfully!")
except Exception as e:
print(f"❌ Error in fill_payment_info: {e}")
driver.switch_to.default_content()
class ToppsBotGUI:
def __init__(self):
self.root = tk.Tk()
self.root.title("Topps Bot Configuration")
self.root.geometry("500x400")
self.root.resizable(False, False)
# Variables
self.bot_mode = tk.StringVar(value="search") # "search" or "url"
self.search_item = tk.StringVar()
self.product_url = tk.StringVar()
self.quantity = tk.StringVar(value="1")
self.driver = None
self.is_running = False
self.create_widgets()
def create_widgets(self):
# Main frame
main_frame = ttk.Frame(self.root, padding="20")
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Title
title_label = ttk.Label(main_frame, text="Topps Bot Configuration",
font=("Arial", 16, "bold"))
title_label.grid(row=0, column=0, columnspan=2, pady=(0, 20))
# Mode Selection
ttk.Label(main_frame, text="Select Mode:").grid(row=1, column=0, sticky=tk.W, pady=5)
mode_frame = ttk.Frame(main_frame)
mode_frame.grid(row=1, column=1, sticky=tk.W, pady=5, padx=(10, 0))
ttk.Radiobutton(mode_frame, text="Search for Item", variable=self.bot_mode,
value="search", command=self.update_mode_visibility).pack(side=tk.LEFT, padx=(0, 10))
ttk.Radiobutton(mode_frame, text="Direct product URL", variable=self.bot_mode,
value="url", command=self.update_mode_visibility).pack(side=tk.LEFT)
# Search Entry (Frame 1)
self.search_frame = ttk.Frame(main_frame)
ttk.Label(self.search_frame, text="Search Item:").grid(row=0, column=0, sticky=tk.W, pady=5)
search_entry = ttk.Entry(self.search_frame, textvariable=self.search_item, width=40)
search_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), pady=5, padx=(10, 0))
# Product URL Entry (Frame 2)
self.url_frame = ttk.Frame(main_frame)
ttk.Label(self.url_frame, text="Product URL:").grid(row=0, column=0, sticky=tk.W, pady=5)
url_entry = ttk.Entry(self.url_frame, textvariable=self.product_url, width=40)
url_entry.grid(row=0, column=1, sticky=(tk.W, tk.E), pady=5, padx=(10, 0))
# Initial Visibility
self.update_mode_visibility()
# Quantity (common)
self.common_frame = ttk.Frame(main_frame)
self.common_frame.grid(row=3, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
ttk.Label(self.common_frame, text="Quantity:").grid(row=0, column=0, sticky=tk.W, pady=5)
quantity_entry = ttk.Entry(self.common_frame, textvariable=self.quantity, width=10)
quantity_entry.grid(row=0, column=1, sticky=tk.W, pady=5, padx=(10, 0))
# Buttons frame
button_frame = ttk.Frame(main_frame)
button_frame.grid(row=4, column=0, columnspan=2, pady=20)
# Start button
self.start_button = ttk.Button(button_frame, text="Start Bot",
command=self.start_bot, style="Accent.TButton")
self.start_button.pack(side=tk.LEFT, padx=5)
# Stop button
self.stop_button = ttk.Button(button_frame, text="Stop Bot",
command=self.stop_bot, state="disabled")
self.stop_button.pack(side=tk.LEFT, padx=5)
# Status frame
status_frame = ttk.LabelFrame(main_frame, text="Status", padding="10")
status_frame.grid(row=5, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=10)
# Status text
self.status_text = tk.Text(status_frame, height=10, width=60, wrap=tk.WORD)
scrollbar = ttk.Scrollbar(status_frame, orient="vertical", command=self.status_text.yview)
self.status_text.configure(yscrollcommand=scrollbar.set)
self.status_text.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
scrollbar.grid(row=0, column=1, sticky=(tk.N, tk.S))
# Configure grid weights
main_frame.columnconfigure(1, weight=1)
status_frame.columnconfigure(0, weight=1)
status_frame.rowconfigure(0, weight=1)
self.search_frame.columnconfigure(1, weight=1)
self.url_frame.columnconfigure(1, weight=1)
def update_mode_visibility(self):
"""Update the visibility of input fields based on selected mode"""
if self.bot_mode.get() == "search":
self.url_frame.grid_forget()
self.search_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
else:
self.search_frame.grid_forget()
self.url_frame.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=5)
def log_message(self, message):
"""Add message to status log"""
self.status_text.insert(tk.END, f"{message}\n")
self.status_text.see(tk.END)
self.root.update_idletasks()
def start_bot(self):
"""Start the bot in a separate thread"""
mode = self.bot_mode.get()
if mode == "search" and not self.search_item.get().strip():
messagebox.showerror("Error", "Please enter a search item")
return
if mode == "url" and not self.product_url.get().strip():
messagebox.showerror("Error", "Please enter a product URL")
return
if not self.quantity.get().strip():
messagebox.showerror("Error", "Please enter a quantity")
return
try:
int(self.quantity.get())
except ValueError:
messagebox.showerror("Error", "Quantity must be a number")
return
self.is_running = True
self.start_button.config(state="disabled")
self.stop_button.config(state="normal")
# Start bot in separate thread
bot_thread = threading.Thread(target=self.run_bot)
bot_thread.daemon = True
bot_thread.start()
def stop_bot(self):
"""Stop the bot"""
self.is_running = False
if self.driver:
try:
self.driver.quit()
except:
pass
self.start_button.config(state="normal")
self.stop_button.config(state="disabled")
self.log_message("🛑 Bot stopped by user")
def purchase_item(self, url, quantity, skip_if_sold_out=False):
"""Complete the purchase flow for a single item URL with wait for availability"""
while self.is_running:
try:
self.log_message(f"📦 Navigating to product: {url}")
self.driver.get(url)
time.sleep(random.randint(3, 5))
close_topps_popups(self.driver)
wait = WebDriverWait(self.driver, 15)
# Check for "Add to cart" button availability
try:
# Look for the add-to-cart button
add_to_cart_button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'button[data-testid="product-add-to-cart"]')))
# Check if it's sold out
is_sold_out = add_to_cart_button.get_attribute("data-sold-out") == "true"
if is_sold_out:
if skip_if_sold_out:
self.log_message(f"⏭️ Item is sold out. Skipping: {url}")
return False
else:
self.log_message("⏳ Item is sold out. Waiting for restock...")
time.sleep(15)
continue
# If not sold out, ensure it's clickable
if not add_to_cart_button.is_enabled():
self.log_message("⏳ Button disabled. Waiting...")
time.sleep(10)
continue
# Find and set quantity
try:
quantity_input = wait.until(EC.element_to_be_clickable((By.NAME, "quantity")))
human_type(quantity_input, quantity, driver=self.driver)
self.log_message(f"✅ Set quantity to: {quantity}")
except:
self.log_message("⚠️ Note: Could not set quantity, using default")
try:
add_to_cart_button.click()
except:
self.driver.execute_script("arguments[0].click();", add_to_cart_button)
self.log_message("✅ Added to cart")
# Break the while loop if successfully added
break
except Exception as e:
self.log_message(f"⏳ Waiting for availability... ({str(e)})")
time.sleep(10)
continue
except Exception as e:
self.log_message(f"❌ Error during purchase attempt: {e}. Retrying...")
time.sleep(5)
continue
# Rest of purchase flow after successfully adding to cart
if not self.is_running: return False
try:
wait = WebDriverWait(self.driver, 15)
time.sleep(random.randint(3, 5))
# Checkout
# Checkout
try:
checkout = self.driver.find_element(By.CSS_SELECTOR, 'a[href="/checkout/cart"]')
checkout_url = checkout.get_attribute('href')
self.driver.get(checkout_url)
except:
# Fallback: directly go to cart URL
self.driver.get("https://www.topps.com/checkout/cart")
self.log_message("🛒 Proceeding to checkout...")
try:
checkoutBtn = wait.until(EC.element_to_be_clickable((By.XPATH, "//*[contains(text(),'checkout')]")))
try:
checkoutBtn.click()
except:
self.driver.execute_script("arguments[0].click();", checkoutBtn)
self.log_message("✅ Checkout button clicked")
except:
self.log_message("❌ Error: Checkout button not found")
return False
# Fill contact form
contactFormFill(self.driver)
time.sleep(random.randint(3, 5))
# Pay Now
self.log_message("💳 Clicking Pay Now...")
try:
payNowBtn = wait.until(EC.element_to_be_clickable((By.ID, "checkout-pay-button")))
try:
payNowBtn.click()
except:
self.driver.execute_script("arguments[0].click();", payNowBtn)
self.log_message("✅ Pay now button clicked")
except:
self.log_message("❌ Error: Pay Now button not found")
return False
self.log_message("🎉 Purchase flow completed for this item!")
time.sleep(5) # Wait for confirmation
return True
except Exception as e:
self.log_message(f"❌ Error during purchase: {e}")
return False
def run_bot(self):
"""Main bot logic"""
try:
self.log_message("🚀 Starting Topps Bot...")
# Create driver
self.log_message("🌐 Starting browser, this may take a moment...")
self.driver = create_driver()
self.log_message("✅ Browser opened successfully")
self.log_message(f"📡 Navigating to {URL}...")
try:
self.driver.get(URL)
self.log_message(f"✅ Loaded {URL}")
except Exception as e:
self.log_message(f"⚠️ Navigation warning: {e}")
# Try one more time or just continue if page partially loaded
pass
# Check for Sign In button
try:
self.log_message("🔍 Looking for Sign In...")
# Give the page a moment to load header elements
time.sleep(5)
# Look for the Sign In link (multiple strategies)
sign_in_link = self.driver.find_elements(By.XPATH, "//a[contains(@href, 'customer/account/login')] | //*[contains(text(), 'Sign In')]")
# Check if any found elements are actually displayed (visible)
is_visible = any(el.is_displayed() for el in sign_in_link)
if is_visible:
self.log_message("🔑 Sign In button detected. Please login manually in the browser.")
# Using messagebox to ensure it pops up and pauses the execution thread
self.log_message("⏸️ Waiting for you to complete login in the browser tab...")
# Show messagebox in a thread-safe way
self.root.after(0, lambda: messagebox.showinfo("Login Required", "Please login to your Topps account manually.\n\nAfter you have successfully logged in, click OK here to continue."))
# We need a way to wait for the OK button if we use root.after,
# but simple messagebox in thread usually works on Windows unless tkinter is weird.
# Let's just log and wait for user to be ready.
self.log_message("ℹ️ Once logged in, the bot will continue automatically in 5 seconds or when you are ready.")
time.sleep(10) # Give user time if messagebox doesn't block properly
self.log_message("✅ Continuing after manual login check...")
except Exception as e:
# If not found or error, just continue to avoid blocking the bot
self.log_message(f"⚠️ Note: Sign in check error: {e}")
pass
product_url = self.product_url.get().strip()
search_item = self.search_item.get().strip()
quantity = self.quantity.get().strip()
mode = self.bot_mode.get()
# Use the selected mode
if mode == "url" and product_url:
self.log_message(f"🚀 Mode: Direct URL. Processing: {product_url}")
self.purchase_item(product_url, quantity)
return
if mode == "search" and search_item:
self.log_message(f"📦 Mode: Search. Searching for: {search_item}")
try:
# Find search input
wait = WebDriverWait(self.driver, 15)
# Try multiple selectors for the search box
search_selectors = [
(By.NAME, "q"),
(By.CSS_SELECTOR, "input[placeholder='Search']"),
(By.CSS_SELECTOR, "input[aria-label='Search']"),
(By.CSS_SELECTOR, "input.no-search-clear")
]
search_box = None
# Make sure we are on a page with search box
if not "topps.com" in self.driver.current_url:
self.driver.get(URL)
time.sleep(2)
for selector in search_selectors:
try:
search_box = wait.until(EC.element_to_be_clickable(selector))
if search_box:
break
except:
continue
if not search_box:
self.log_message("❌ Error: Could not find search box")
return
# Perform search
search_box.click()
human_type(search_box, search_item, driver=self.driver)
search_box.send_keys(Keys.ENTER)
time.sleep(random.randint(3, 5))
close_topps_popups(self.driver)
# Check "IN STOCK ONLY"
try:
self.log_message("🔍 Applying 'IN STOCK ONLY' filter...")
in_stock_selectors = [
(By.ID, "stock_status_filter"),
(By.CSS_SELECTOR, "#stock_status_filter"),
(By.CSS_SELECTOR, "[data-testid='checkbox']#stock_status_filter"),
(By.XPATH, "//*[contains(text(), 'In Stock Only')]"),
(By.XPATH, "//label[contains(., 'In Stock Only')]")
]
found_filter = False
for selector in in_stock_selectors:
try:
filter_el = wait.until(EC.presence_of_element_located(selector))
if filter_el.is_displayed():
aria_checked = filter_el.get_attribute("aria-checked")
if aria_checked == "true":
self.log_message("✅ 'IN STOCK ONLY' filter already applied")
found_filter = True
break
try:
filter_el.click()
except:
self.driver.execute_script("arguments[0].click();", filter_el)
found_filter = True
self.log_message("✅ applied 'IN STOCK ONLY' filter")
time.sleep(2)
break
except:
continue
except Exception as e:
self.log_message(f"⚠️ Error applying filter: {e}")
# Collect all product URLs
self.log_message("🔍 Collecting product URLs from results...")
product_urls = []
retry_count = 0
while self.is_running:
time.sleep(3) # Wait for filter to apply and results to load
# Using the a.contents selector provided by the user
product_links = self.driver.find_elements(By.CSS_SELECTOR, 'a.contents[href*="/products/"]')
for link in product_links:
url = link.get_attribute("href")
if url and url not in product_urls:
if not url.startswith("http"):
url = "https://www.topps.com" + url
product_urls.append(url)
if product_urls:
self.log_message(f"✅ Found {len(product_urls)} products in results")
break
else:
retry_count += 1
self.log_message(f"⏳ No in-stock products found (Attempt {retry_count}). Waiting 15s...")
time.sleep(15)
self.driver.refresh()
time.sleep(5)
# Re-apply filter if necessary (or search again)
# For simplicity, let's assume refresh keeps filter or we need to re-click
# Re-click filter
try:
for selector in in_stock_selectors:
try:
filter_el = wait.until(EC.presence_of_element_located(selector))
if filter_el.is_displayed():
aria_checked = filter_el.get_attribute("aria-checked")
if aria_checked != "true":
self.driver.execute_script("arguments[0].click();", filter_el)
time.sleep(3)
break
except:
continue
except:
pass
# Buy one by one
for idx, url in enumerate(product_urls):
if not self.is_running: break
self.log_message(f"🛒 Processing item {idx+1}/{len(product_urls)}")
# Skip if sold out during search results loop
self.purchase_item(url, quantity, skip_if_sold_out=True)
# Optionally clear cart if items persist (usually checkout does this)
time.sleep(2)
except Exception as e:
self.log_message(f"❌ Search or loop Error: {str(e)}")
return
except Exception as e:
self.log_message(f"❌ Fatal Error: {str(e)}")
finally:
self.is_running = False
self.start_button.config(state="normal")
self.stop_button.config(state="disabled")
def run(self):
"""Start the GUI"""
self.root.mainloop()
def main():
"""Main function to start the GUI"""
app = ToppsBotGUI()
app.run()
if __name__ == "__main__":
main()