-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_status_checker.py
More file actions
766 lines (640 loc) · 32.7 KB
/
http_status_checker.py
File metadata and controls
766 lines (640 loc) · 32.7 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
import asyncio
import httpx
import io
from bs4 import BeautifulSoup
from datetime import datetime
import xml.etree.ElementTree as ET
from tqdm import tqdm
import csv
import argparse
import sys
from typing import List, Dict, Optional, Set, Tuple
import time
import warnings
from urllib.parse import urljoin, urlparse
import json
from pathlib import Path
import queue
import threading
from dataclasses import dataclass, field
from concurrent.futures import ThreadPoolExecutor
import aiofiles
import os
from colorama import init, Fore, Back, Style
# Colorama'yı başlat
init(autoreset=True)
# XML uyarılarını gizle
warnings.filterwarnings('ignore', category=UserWarning, module='bs4')
def print_header(text: str):
print(f"\n{Fore.CYAN}{Style.BRIGHT}{'='*20} {text} {'='*20}{Style.RESET_ALL}")
def print_success(text: str):
print(f"{Fore.GREEN}{text}{Style.RESET_ALL}")
def print_info(text: str):
print(f"{Fore.BLUE}{text}{Style.RESET_ALL}")
def print_warning(text: str):
print(f"{Fore.YELLOW}{text}{Style.RESET_ALL}")
def print_error(text: str):
print(f"{Fore.RED}{text}{Style.RESET_ALL}")
def print_stats(title: str, stats: Dict):
print(f"\n{Fore.MAGENTA}{Style.BRIGHT}{'='*10} {title} {'='*10}{Style.RESET_ALL}")
for key, value in stats.items():
print(f"{Fore.CYAN}{key}: {Fore.WHITE}{value}{Style.RESET_ALL}")
@dataclass
class DOMElement:
tag: str
attribute: str
url: str
text: str
source_url: str
class RateLimiter:
"""URL/saniye hız sınırlayıcı"""
def __init__(self, max_rate: float):
self.max_rate = max_rate # Saniyedeki maksimum istek sayısı
self.tokens = max_rate # Mevcut token sayısı
self.last_update = time.monotonic()
self.lock = asyncio.Lock()
self.enabled = True # Hız sınırı aktif/pasif
def disable(self):
"""Hız sınırını devre dışı bırak"""
self.enabled = False
def enable(self):
"""Hız sınırını etkinleştir"""
self.enabled = True
async def acquire(self):
"""Bir token al ve gerekirse bekle"""
if not self.enabled:
return
async with self.lock:
now = time.monotonic()
time_passed = now - self.last_update
self.tokens = min(self.max_rate, self.tokens + time_passed * self.max_rate)
self.last_update = now
if self.tokens < 1:
wait_time = (1 - self.tokens) / self.max_rate
await asyncio.sleep(wait_time)
self.tokens = 0
self.last_update = time.monotonic()
else:
self.tokens -= 1
class AsyncHTTPStatusChecker:
def __init__(self, base_domain: str, max_workers: int = 5, timeout: int = 30,
batch_size: int = 50, output_dir: str = 'output', max_rate: float = 2):
self.base_domain = base_domain.lower() # Ana domain
self.max_workers = max_workers
self.timeout = timeout
self.batch_size = batch_size
self.output_dir = Path(output_dir)
self.rate_limiter = RateLimiter(max_rate)
self.output_dir.mkdir(exist_ok=True)
# DOM elementleri için izlenecek özellikler
self.dom_targets = {
'a': ['href'],
'img': ['src', 'data-src'],
'link': ['href'],
'form': ['action'],
}
# Sayaçlar ve istatistikler
self.dom_stats = {tag: 0 for tag in self.dom_targets.keys()}
self.discovered_urls = set()
# Dosya yolları
self.sitemap_urls_file = self.output_dir / 'sitemap_urls.txt'
self.sitemap_list_file = self.output_dir / 'sitemap_list.txt' # Sitemap'lerin kendisi için
self.crawled_urls_file = self.output_dir / 'crawled_urls.txt'
self.dom_elements_file = self.output_dir / 'dom_elements.csv'
self.results_file = self.output_dir / 'results.csv'
self.stats_file = self.output_dir / 'stats.json'
# Asenkron kilitler
self.file_lock = asyncio.Lock()
# İlerleme çubuğu
self.progress_bar = None
# Callback'ler
self._progress_callback = None
self._stage_callback = None
self._stats_callback = None
# Dosyaları hazırla
self._init_files()
def set_callbacks(self, progress_callback=None, stage_callback=None, stats_callback=None):
"""GUI için callback'leri ayarla"""
self._progress_callback = progress_callback
self._stage_callback = stage_callback
self._stats_callback = stats_callback
async def _emit_progress(self, message: str):
"""İlerleme mesajı gönder"""
if self._progress_callback:
await self._progress_callback(message)
else:
print(message)
async def _emit_stage(self, stage: str):
"""Aşama değişikliği bildir"""
if self._stage_callback:
await self._stage_callback(stage)
else:
print_header(stage)
async def _emit_stats(self, stats: dict):
"""İstatistik güncelleme bildir"""
if self._stats_callback:
await self._stats_callback(stats)
else:
print_stats("İstatistikler", stats)
def is_same_domain(self, url: str) -> bool:
"""URL'nin ana domain'e veya subdomain'e ait olup olmadığını kontrol et"""
try:
if not url.startswith(('http://', 'https://')):
return False
domain = urlparse(url).netloc.lower()
return domain.endswith(self.base_domain)
except:
return False
def _init_files(self):
# URL dosyaları
for file in [self.sitemap_urls_file, self.crawled_urls_file, self.sitemap_list_file]:
file.touch()
# DOM elementleri CSV'si
dom_fieldnames = ['tag', 'attribute', 'url', 'text', 'source_url']
with open(self.dom_elements_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=dom_fieldnames)
writer.writeheader()
# Sonuçlar CSV'si
result_fieldnames = ['url', 'status_code', 'title', 'h1', 'h2', 'check_date', 'source', 'error']
with open(self.results_file, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=result_fieldnames)
writer.writeheader()
async def add_url_to_file(self, url: str, file: Path):
if self.is_same_domain(url): # Sadece kendi domain'imize ait URL'leri kaydet
async with self.file_lock:
async with aiofiles.open(file, 'a', encoding='utf-8') as f:
await f.write(f"{url}\n")
async def read_urls_from_file(self, file: Path) -> Set[str]:
urls = set()
try:
async with aiofiles.open(file, 'r', encoding='utf-8') as f:
async for line in f:
url = line.strip()
if self.is_same_domain(url): # Sadece kendi domain'imize ait URL'leri oku
urls.add(url)
except:
pass
return urls
async def add_dom_element(self, element: DOMElement):
if self.is_same_domain(element.url): # Sadece kendi domain'imize ait elementleri kaydet
async with self.file_lock:
async with aiofiles.open(self.dom_elements_file, 'a', newline='', encoding='utf-8') as f:
row = {
'tag': element.tag,
'attribute': element.attribute,
'url': element.url,
'text': element.text,
'source_url': element.source_url
}
await f.write(','.join(f'"{str(v)}"' for v in row.values()) + '\n')
self.dom_stats[element.tag] += 1
async def add_result(self, result: Dict):
if self.is_same_domain(result['url']): # Sadece kendi domain'imize ait sonuçları kaydet
async with self.file_lock:
async with aiofiles.open(self.results_file, 'a', newline='', encoding='utf-8') as f:
await f.write(','.join(f'"{str(result[key])}"' for key in result.keys()) + '\n')
# AŞAMA 1: Sitemap Keşfi
async def check_sitemap_status(self, sitemap_url: str, depth: int = 0) -> Tuple[bool, Optional[str]]:
"""Sitemap'in durumunu kontrol et ve içeriğini döndür"""
indent = " " * depth
try:
await self.rate_limiter.acquire() # Hız sınırlaması uygula
async with httpx.AsyncClient() as client:
response = await client.get(sitemap_url, timeout=self.timeout)
if response.status_code == 200:
await self._emit_progress(f"{indent}✓ Sitemap erişilebilir ({response.status_code}): {sitemap_url}")
return True, response.text
else:
await self._emit_progress(f"{indent}✗ Sitemap hatası ({response.status_code}): {sitemap_url}")
return False, None
except Exception as e:
await self._emit_progress(f"{indent}✗ Sitemap bağlantı hatası: {sitemap_url} - {str(e)}")
return False, None
async def discover_sitemap_urls(self, sitemap_url: str, depth: int = 0) -> None:
"""Sitemap'ten tüm URL'leri keşfet (sitemap'ler dahil) - Paralel keşif"""
indent = " " * depth
# Keşif istatistikleri
if not hasattr(self, 'discovery_stats'):
self.discovery_stats = {
'start_time': time.time(),
'sitemap_count': 0,
'url_count': 0,
'error_count': 0,
'last_error': None,
'last_error_time': None
}
self.discovery_progress = tqdm(desc="Keşif İlerlemesi", unit=" URL")
# Önce bu sitemap'i kaydet
await self.add_url_to_file(sitemap_url, self.sitemap_list_file)
self.discovery_stats['sitemap_count'] += 1
try:
# HTTP istemci ayarları
limits = httpx.Limits(max_keepalive_connections=50, max_connections=50)
normal_timeout = httpx.Timeout(connect=5.0, read=10.0, write=5.0, pool=10.0)
extended_timeout = httpx.Timeout(connect=10.0, read=30.0, write=10.0, pool=30.0)
content = None
# İlk deneme - normal timeout ile
try:
async with httpx.AsyncClient(limits=limits, timeout=normal_timeout) as client:
response = await client.get(sitemap_url, follow_redirects=True)
if response.status_code == 200:
content = response.text
except httpx.TimeoutException:
# Timeout durumunda uzun timeout ile tekrar dene
await self._emit_progress(f"{indent}{Fore.YELLOW}⟳ Timeout - tekrar deneniyor (30s): {sitemap_url}{Style.RESET_ALL}")
async with httpx.AsyncClient(limits=limits, timeout=extended_timeout) as client:
response = await client.get(sitemap_url, follow_redirects=True)
if response.status_code == 200:
content = response.text
await self._emit_progress(f"{indent}{Fore.GREEN}✓ İçerik alındı: {sitemap_url}{Style.RESET_ALL}")
# HTTP durum kodunu kontrol et
if not content:
if response.status_code == 403:
error_msg = "Erişim engellendi (403) - Güvenlik duvarı veya rate limit"
self.discovery_stats['error_count'] += 1
await self._emit_progress(f"{indent}✗ {error_msg}: {sitemap_url}")
return
elif response.status_code == 429:
error_msg = "Çok fazla istek (429) - Rate limit aşıldı"
self.discovery_stats['error_count'] += 1
await self._emit_progress(f"{indent}✗ {error_msg}: {sitemap_url}")
return
elif response.status_code != 200:
error_msg = f"HTTP {response.status_code}"
self.discovery_stats['error_count'] += 1
await self._emit_progress(f"{indent}✗ {error_msg}: {sitemap_url}")
return
content = response.text
if not content:
await self._emit_progress(f"{indent}{Fore.RED}✗ İçerik alınamadı: {sitemap_url}{Style.RESET_ALL}")
return
# Debug bilgileri
await self._emit_progress(f"\n{indent}{Fore.CYAN}XML içeriği analiz ediliyor...{Style.RESET_ALL}")
await self._emit_progress(f"{indent}{Fore.CYAN}İçerik örneği: {content[:200]}...{Style.RESET_ALL}")
# XML'i parse et
root = ET.fromstring(content)
# Namespace'leri bul
nsmap = {}
for _, (prefix, uri) in ET.iterparse(io.StringIO(content), events=['start-ns']):
nsmap[prefix] = uri
await self._emit_progress(f"{indent}Namespace bulundu: {prefix} = {uri}")
# Tüm URL'leri topla
all_locs = []
# Önce standart sitemap URL'lerini kontrol et
for url in root.findall('.//{http://www.sitemaps.org/schemas/sitemap/0.9}loc'):
all_locs.append(url)
# Sonra resim sitemap'lerini kontrol et
for url in root.findall('.//{http://www.google.com/schemas/sitemap-image/1.1}loc'):
all_locs.append(url)
await self._emit_progress(f"{indent}Toplam {len(all_locs)} URL bulundu")
# URL'leri ve sitemap'leri ayır
sub_tasks = []
for loc in all_locs:
url = loc.text.strip()
if not self.is_same_domain(url):
continue
if url.endswith('.xml'):
# Sitemap - paralel keşif için task oluştur
sub_tasks.append(asyncio.create_task(self.discover_sitemap_urls(url, depth + 1)))
else:
# Normal URL - direkt kaydet
await self.add_url_to_file(url, self.sitemap_urls_file)
self.discovery_stats['url_count'] += 1
self.discovery_progress.update(1)
# Hız hesapla
elapsed = time.time() - self.discovery_stats['start_time']
speed = self.discovery_stats['url_count'] / elapsed if elapsed > 0 else 0
# Progress bar açıklamasını güncelle
self.discovery_progress.set_description(
f"Keşif ({speed:.1f} URL/s) "
f"[URL: {self.discovery_stats['url_count']:,} | "
f"Sitemap: {self.discovery_stats['sitemap_count']:,} | "
f"Hata: {self.discovery_stats['error_count']:,}]"
)
# Alt sitemap'leri paralel işle
if sub_tasks:
await self._emit_progress(f"{indent}{Fore.BLUE}→ {len(sub_tasks)} alt sitemap paralel işleniyor{Style.RESET_ALL}")
await asyncio.gather(*sub_tasks)
await self._emit_progress(f"{indent}{Fore.GREEN}✓ Alt sitemap'ler tamamlandı{Style.RESET_ALL}")
except httpx.TimeoutException as e:
# İkinci timeout hatası - bu URL'yi tekrar kuyruğa al
self.discovery_stats['error_count'] += 1
await self._emit_progress(f"{indent}{Fore.YELLOW}⟳ İkinci timeout - tekrar kuyruğa alındı: {sitemap_url}{Style.RESET_ALL}")
# 5 saniye bekle ve tekrar dene
await asyncio.sleep(5)
await self.discover_sitemap_urls(sitemap_url, depth)
return
except (ET.ParseError, Exception) as e:
self.discovery_stats['error_count'] += 1
error_msg = str(e) if str(e) else e.__class__.__name__
await self._emit_progress(f"{indent}{Fore.RED}✗ XML işleme hatası: {sitemap_url} - {error_msg}{Style.RESET_ALL}")
return # Hata durumunda fonksiyondan çık
# URL'leri ve sitemap'leri ayır
sub_tasks = []
for loc in all_locs:
url = loc.text.strip()
if not self.is_same_domain(url):
continue
if url.endswith('.xml'):
# Sitemap - paralel keşif için task oluştur
sub_tasks.append(asyncio.create_task(self.discover_sitemap_urls(url, depth + 1)))
else:
# Normal URL - direkt kaydet
await self.add_url_to_file(url, self.sitemap_urls_file)
self.discovery_stats['url_count'] += 1
self.discovery_progress.update(1)
# Hız hesapla
elapsed = time.time() - self.discovery_stats['start_time']
speed = self.discovery_stats['url_count'] / elapsed if elapsed > 0 else 0
# Progress bar açıklamasını güncelle
self.discovery_progress.set_description(
f"Keşif ({speed:.1f} URL/s) "
f"[URL: {self.discovery_stats['url_count']:,} | "
f"Sitemap: {self.discovery_stats['sitemap_count']:,} | "
f"Hata: {self.discovery_stats['error_count']:,}]"
)
# Tüm sitemap'leri paralel işle
if sub_tasks:
await self._emit_progress(f"{indent}→ {len(sub_tasks)} alt sitemap paralel işleniyor")
await asyncio.gather(*sub_tasks)
# URL'leri topla ve kaydet (XML olmayanlar)
page_urls = []
url_patterns = [
'.//sm:url/sm:loc', # Standart namespace
'.//url/loc', # Namespace'siz
'.//*[local-name()="url"]/*[local-name()="loc"]' # Local name
]
# Bu sitemap'teki URL'leri bul
for pattern in url_patterns:
try:
found = root.findall(pattern, sitemap_ns)
if found:
page_urls.extend(found)
except:
continue
# Bulunan URL'leri dosyaya kaydet (XML olmayanlar)
url_count = 0
for url in page_urls:
url_str = url.text.strip().split('#')[0].split('?')[0]
if self.is_same_domain(url_str) and not url_str.endswith('.xml'):
await self.add_url_to_file(url_str, self.sitemap_urls_file)
url_count += 1
if url_count > 0:
await self._emit_progress(f"{indent}✓ {url_count} URL kaydedildi: {sitemap_url}")
else:
await self._emit_progress(f"{indent}! URL bulunamadı: {sitemap_url}")
except Exception as e:
await self._emit_progress(f"{indent}✗ Sitemap ayrıştırma hatası: {sitemap_url} - {str(e)}")
# AŞAMA 2: DOM Keşfi
async def discover_dom_elements(self, url: str, client: httpx.AsyncClient) -> Set[str]:
new_urls = set()
try:
response = await client.get(url, timeout=self.timeout, follow_redirects=True)
soup = BeautifulSoup(response.text, 'html.parser')
for tag, attributes in self.dom_targets.items():
for element in soup.find_all(tag):
for attr in attributes:
if href := element.get(attr):
full_url = urljoin(url, href)
clean_url = full_url.split('#')[0].split('?')[0]
if self.is_same_domain(clean_url): # Sadece kendi domain'imize ait URL'leri işle
if clean_url not in self.discovered_urls:
new_urls.add(clean_url)
self.discovered_urls.add(clean_url)
await self.add_url_to_file(clean_url, self.crawled_urls_file)
text = element.get_text(strip=True) if element.string else ''
dom_element = DOMElement(
tag=tag,
attribute=attr,
url=clean_url,
text=text,
source_url=url
)
await self.add_dom_element(dom_element)
except Exception as e:
await self._emit_progress(f"DOM keşif hatası ({url}): {e}")
return new_urls
async def crawl_for_dom_elements(self, start_url: str, max_depth: int = 3):
await self._emit_stage("DOM Keşif Aşaması")
visited = set()
to_visit = {start_url}
current_depth = 0
limits = httpx.Limits(max_keepalive_connections=self.max_workers, max_connections=self.max_workers)
timeout = httpx.Timeout(self.timeout)
# Semaphore'u burada oluştur
semaphore = asyncio.Semaphore(self.max_workers)
async def process_url(url: str, client: httpx.AsyncClient) -> Set[str]:
"""Tek bir URL'yi işle"""
async with semaphore: # Semaphore ile istek sayısını sınırla
if url not in visited and self.is_same_domain(url):
return await self.discover_dom_elements(url, client)
return set()
async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:
with tqdm(desc="Crawling derinliği", total=max_depth) as pbar:
while to_visit and current_depth < max_depth:
current_urls = list(to_visit)
to_visit.clear()
# URL'leri batch'lere böl
batches = [current_urls[i:i + self.batch_size] for i in range(0, len(current_urls), self.batch_size)]
for batch in batches:
tasks = [process_url(url, client) for url in batch]
if tasks:
results = await asyncio.gather(*tasks)
for new_urls in results:
to_visit.update(new_urls - visited)
visited.update(current_urls)
current_depth += 1
pbar.update(1)
await self._emit_stats({
"Derinlik": current_depth,
"Ziyaret Edilen URL": len(visited),
"Kuyrukta Bekleyen URL": len(to_visit),
**{f"{tag} sayısı": count for tag, count in self.dom_stats.items() if count > 0}
})
# AŞAMA 3: HTTP Durum Kodu Kontrolü
async def check_http_status(self, url_info: Tuple[str, str], client: httpx.AsyncClient) -> Dict:
url, source = url_info
if not self.is_same_domain(url): # Sadece kendi domain'imize ait URL'leri kontrol et
return None
try:
await self.rate_limiter.acquire() # Hız sınırlaması uygula
response = await client.get(url, timeout=self.timeout, follow_redirects=True)
soup = BeautifulSoup(response.text, 'html.parser')
title = soup.title.string if soup.title else ''
h1 = soup.find('h1').text if soup.find('h1') else ''
h2 = soup.find('h2').text if soup.find('h2') else ''
result = {
'url': url,
'status_code': response.status_code,
'title': title.strip() if title else '',
'h1': h1.strip() if h1 else '',
'h2': h2.strip() if h2 else '',
'check_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'source': source
}
await self.add_result(result)
return result
except Exception as e:
result = {
'url': url,
'status_code': 0,
'title': '',
'h1': '',
'h2': '',
'check_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'error': str(e),
'source': source
}
await self.add_result(result)
return result
finally:
if self.progress_bar:
self.progress_bar.update(1)
async def check_all_urls(self):
await self._emit_stage("HTTP Durum Kodu Kontrol Aşaması")
# Tüm URL'leri topla
sitemap_urls = await self.read_urls_from_file(self.sitemap_urls_file)
crawled_urls = await self.read_urls_from_file(self.crawled_urls_file)
all_urls = sitemap_urls.union(crawled_urls)
# Sadece kendi domain'imize ait URL'leri filtrele
all_urls = {url for url in all_urls if self.is_same_domain(url)}
if not all_urls:
await self._emit_progress("Kontrol edilecek URL bulunamadı!")
return
await self._emit_progress(f"Toplam {len(all_urls)} URL kontrol edilecek")
self.progress_bar = tqdm(total=len(all_urls), desc="URL'ler kontrol ediliyor")
# URL'leri batch'lere böl
url_list = [(url, 'sitemap' if url in sitemap_urls else 'crawl') for url in all_urls]
batches = [url_list[i:i + self.batch_size] for i in range(0, len(url_list), self.batch_size)]
# HTTP istemci ayarları
limits = httpx.Limits(
max_keepalive_connections=self.max_workers * 2, # Daha fazla bağlantı tut
max_connections=self.max_workers * 2,
keepalive_expiry=30.0 # Bağlantıları daha uzun süre tut
)
timeout = httpx.Timeout(
connect=5.0, # Bağlantı timeout'u
read=self.timeout, # Okuma timeout'u
write=5.0, # Yazma timeout'u
pool=10.0 # Havuz timeout'u
)
# Semaphore'u burada oluştur
semaphore = asyncio.Semaphore(self.max_workers)
async def process_url_status(url_info: Tuple[str, str], client: httpx.AsyncClient) -> Optional[Dict]:
"""Tek bir URL'nin durumunu kontrol et"""
async with semaphore: # Semaphore ile istek sayısını sınırla
try:
return await self.check_http_status(url_info, client)
except Exception as e:
await self._emit_progress(f"Hata ({url_info[0]}): {str(e)}")
return None
# Her batch için yeni bir client oluştur
for batch in batches:
async with httpx.AsyncClient(limits=limits, timeout=timeout) as client:
tasks = [process_url_status(url_info, client) for url_info in batch]
if tasks:
await asyncio.gather(*tasks)
self.progress_bar.close()
async def save_stats(self):
stats = {
'sitemap_urls': len(await self.read_urls_from_file(self.sitemap_urls_file)),
'crawled_urls': len(await self.read_urls_from_file(self.crawled_urls_file)),
'dom_elements': self.dom_stats,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
async with aiofiles.open(self.stats_file, 'w', encoding='utf-8') as f:
await f.write(json.dumps(stats, indent=2, ensure_ascii=False))
await self._emit_stage("Sonuç İstatistikleri")
await self._emit_progress(f"Sonuçlar {self.output_dir} dizinine kaydedildi.")
await self._emit_stats({
"Sitemap URL'leri": stats['sitemap_urls'],
"Crawl URL'leri": stats['crawled_urls'],
"Toplam URL": stats['sitemap_urls'] + stats['crawled_urls'],
"DOM Elementleri": {
tag: count for tag, count in self.dom_stats.items() if count > 0
}
})
async def main():
parser = argparse.ArgumentParser(description='HTTP Status Kod Kontrol Aracı')
parser.add_argument('--sitemap', type=str, help='Sitemap XML URL')
parser.add_argument('--sitemaps-file', type=str, help='Sitemap listesi içeren dosya (her satırda bir URL)')
parser.add_argument('--url', type=str, help='Başlangıç URL')
parser.add_argument('--workers', type=int, default=5, help='Eşzamanlı işlem sayısı')
parser.add_argument('--batch-size', type=int, default=50, help='Her batch\'teki URL sayısı')
parser.add_argument('--output-dir', type=str, default='output', help='Çıktı dizini')
parser.add_argument('--timeout', type=int, default=30, help='Sayfa zaman aşımı (saniye)')
parser.add_argument('--depth', type=int, default=3, help='Crawling derinliği')
parser.add_argument('--max-rate', type=float, default=2, help='Saniyedeki maksimum istek sayısı')
parser.add_argument('--ignore-rate-limit-discovery', action='store_true', help='Keşif sırasında hız sınırını devre dışı bırak')
args = parser.parse_args()
if not args.sitemap and not args.sitemaps_file and not args.url:
print_error("Sitemap URL, sitemap listesi veya başlangıç URL'i gerekli!")
sys.exit(1)
# Sitemap listesini oku
sitemaps = set()
if args.sitemaps_file:
try:
with open(args.sitemaps_file, 'r', encoding='utf-8') as f:
sitemaps.update(line.strip() for line in f if line.strip())
except Exception as e:
print_error(f"Sitemap listesi okuma hatası: {e}")
sys.exit(1)
if args.sitemap:
sitemaps.add(args.sitemap)
if sitemaps:
print_info(f"Toplam {len(sitemaps)} sitemap işlenecek")
# İlk sitemap'ten domain'i belirle
base_domain = urlparse(next(iter(sitemaps))).netloc.lower()
if base_domain.startswith('www.'):
base_domain = base_domain[4:]
else:
base_domain = urlparse(args.url).netloc.lower()
if base_domain.startswith('www.'):
base_domain = base_domain[4:]
print_info(f"Ana domain: {base_domain}")
checker = AsyncHTTPStatusChecker(
base_domain=base_domain,
max_workers=args.workers,
timeout=args.timeout,
batch_size=args.batch_size,
output_dir=args.output_dir,
max_rate=args.max_rate
)
# AŞAMA 1: URL Keşfi
if sitemaps:
print_header("URL Keşif Aşaması")
# Keşif sırasında hız sınırını kontrol et
if args.ignore_rate_limit_discovery:
print_info("Keşif sırasında hız sınırı devre dışı")
checker.rate_limiter.disable()
# Tüm URL'leri keşfet ve kaydet
for sitemap_url in sitemaps:
await checker.discover_sitemap_urls(sitemap_url)
# Hız sınırını tekrar etkinleştir
if args.ignore_rate_limit_discovery:
print_info("Hız sınırı tekrar etkinleştirildi")
checker.rate_limiter.enable()
# Keşfedilen tüm URL'leri oku
all_urls = set()
# Sitemap'leri oku
async with aiofiles.open(checker.sitemap_list_file, 'r', encoding='utf-8') as f:
async for line in f:
all_urls.add(line.strip())
# Normal URL'leri oku
async with aiofiles.open(checker.sitemap_urls_file, 'r', encoding='utf-8') as f:
async for line in f:
all_urls.add(line.strip())
if all_urls:
print_header(f"HTTP Durum Kodu Kontrol Aşaması ({len(all_urls)} URL)")
# Tüm URL'lerin durum kodlarını kontrol et
for url in all_urls:
await checker.check_http_status((url, 'sitemap'), httpx.AsyncClient())
# AŞAMA 2: DOM Keşfi
if args.url:
await checker.crawl_for_dom_elements(args.url, args.depth)
# AŞAMA 3: HTTP Durum Kodu Kontrolü
await checker.check_all_urls()
# İstatistikleri kaydet
await checker.save_stats()
if __name__ == '__main__':
asyncio.run(main())