Repository navigation
Expand file tree
/
Copy pathdorkwright.py
More file actions
923 lines (772 loc) · 34.9 KB
/
Copy pathdorkwright.py
File metadata and controls
923 lines (772 loc) · 34.9 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
#!/usr/bin/env python3
import argparse
import asyncio
import os
import re
import sys
from pathlib import Path
from urllib.parse import (
parse_qs,
parse_qsl,
quote_plus,
unquote,
urlencode,
urljoin,
urlparse,
)
from playwright.async_api import async_playwright
import requests
from tqdm import tqdm
async def has_captcha(page) -> bool:
"""Return True only when the current page is a Google challenge."""
parsed_url = urlparse(page.url)
hostname = (parsed_url.hostname or "").lower()
if hostname == "google.com" or hostname.endswith(".google.com"):
if parsed_url.path.startswith("/sorry/"):
return True
return await page.evaluate(
"""
() => {
// Ordinary result pages contain CAPTCHA-related scripts, so only
// inspect elements which identify an actual challenge page.
if (document.querySelector('form#captcha-form')) return true;
if (document.querySelector('.g-recaptcha')) return true;
if (document.querySelector('[data-sitekey]')) return true;
if (document.querySelector('#infoDiv')) return true;
if (document.querySelector('iframe[src*="/sorry/"], iframe[src*="recaptcha"]')) return true;
return false;
}
"""
)
async def wait_for_captcha(page) -> None:
"""Pause until the user has really cleared Google's challenge."""
first_prompt = True
while await has_captcha(page):
print("\n" + "=" * 60)
print("CAPTCHA DETECTED!" if first_prompt else "CAPTCHA IS STILL ACTIVE!")
print("Please finish the CAPTCHA in the browser window.")
print("Press ENTER here when the Google results are visible...")
print("=" * 60 + "\n")
# Keep the asyncio loop responsive while waiting for console input.
await asyncio.to_thread(input)
await page.wait_for_timeout(1000)
first_prompt = False
async def resolve_google_result_url(url: str, request_context) -> str | None:
"""Resolve Google's opaque /goto token without downloading the target file."""
parsed = urlparse(url)
hostname = (parsed.hostname or "").lower()
is_google_host = hostname == "google.com" or hostname.endswith(".google.com")
if is_google_host and parsed.path == "/goto":
try:
response = await request_context.get(
url,
max_redirects=0,
timeout=30000,
)
if response.status in {301, 302, 303, 307, 308}:
location = response.headers.get("location")
if location:
return clean_google_url(urljoin(url, location))
except Exception as error:
print(f" Could not resolve Google result link: {error}")
return None
return clean_google_url(url)
async def extract_file_links(query: str, max_pages: int = 10, delay: int = 3):
file_links = set()
query_filetypes = extract_query_filetypes(query)
async with async_playwright() as p:
# Keep cookies and challenge clearance between runs. A fresh temporary
# browser context on every run makes Google challenge the script more often.
profile_dir = Path(__file__).resolve().parent / ".dorkwright-browser"
context = await p.chromium.launch_persistent_context(
user_data_dir=str(profile_dir),
headless=False,
viewport={"width": 1600, "height": 900},
locale="en-US",
)
page = context.pages[0] if context.pages else await context.new_page()
for page_num in range(max_pages):
try:
# Construct Google search URL
start = page_num * 10
search_url = f"https://www.google.com/search?q={quote_plus(query)}&start={start}"
print(f"Searching page {page_num + 1}...", flush=True)
await page.goto(search_url, wait_until="networkidle", timeout=30000)
# Handle cookie consent if present
try:
# Look for common Google consent buttons
consent_buttons = [
'button:has-text("Accept all")',
'button:has-text("Reject all")',
'button:has-text("I agree")',
"#L2AGLb", # Google's "Accept all" button ID
'button[id="W0wltc"]', # Another common consent button
]
for selector in consent_buttons:
try:
button = page.locator(selector).first
if await button.is_visible(timeout=2000):
print(f" Handling cookie consent...", flush=True)
await button.click()
await page.wait_for_timeout(1000)
break
except:
continue
except Exception as e:
pass # No consent dialog, continue
# Wait a bit for dynamic content
await page.wait_for_timeout(2000)
# Never parse or paginate a challenge page. Pressing ENTER too
# early previously made every subsequent page appear empty.
await wait_for_captcha(page)
# Extract links together with nearby result text. Google may show
# file results whose destination URL has no extension, e.g.
# /document_2671 with a visible "PDF" badge in the result card.
candidates = await page.evaluate(
"""
() => {
const resultSelectors = [
'div.g',
'div.MjjYud',
'[data-sokoban-container]',
'div[data-header-feature]'
];
const resultContainerFor = (anchor) => {
for (const selector of resultSelectors) {
const container = anchor.closest(selector);
if (container) return container;
}
return anchor.parentElement;
};
return Array.from(document.querySelectorAll('a[href]')).map(a => {
const container = resultContainerFor(a);
return {
href: a.href,
hasHeading: Boolean(a.querySelector('h3')),
anchorText: a.innerText || '',
resultText: container ? (container.innerText || '') : ''
};
});
}
"""
)
# Filter for direct file links and Google-labeled file results
for candidate in candidates:
clean_link = await resolve_google_result_url(
candidate.get("href", ""), context.request
)
if not clean_link:
continue
result_text = " ".join(
[
candidate.get("anchorText", ""),
candidate.get("resultText", ""),
]
)
is_google_labeled_file = candidate.get(
"hasHeading"
) and is_labeled_file_result(result_text, query_filetypes)
if is_file_link(clean_link) or is_google_labeled_file:
if clean_link not in file_links:
file_links.add(clean_link)
print(f" Found: {clean_link}")
if not candidates:
print(f" Google returned no links on {page.url}")
# Check if there's a "Next" button. Google changes the ID from
# time to time, so also recognize a forward /search?start= link.
has_next = await page.evaluate(
"""
() => {
if (document.querySelector(
'a#pnnext, a[aria-label="Next page"], a[aria-label="Next"]'
)) return true;
const currentStart = Number(
new URL(location.href).searchParams.get('start') || 0
);
return Array.from(document.querySelectorAll('a[href]')).some(a => {
try {
const url = new URL(a.href, location.href);
return url.pathname === '/search'
&& Number(url.searchParams.get('start')) > currentStart;
} catch (_) {
return false;
}
});
}
"""
)
if not has_next:
if page_num + 1 < max_pages:
print(
f"No more pages available. Scraped {page_num + 1} of {max_pages} requested pages."
)
else:
print("Reached last page of results.")
break
# Delay before next page to avoid triggering anti-bot measures
if page_num < max_pages - 1:
print(f" Waiting {delay} seconds before next page...", flush=True)
await page.wait_for_timeout(delay * 1000)
except Exception as e:
print(f"Error on page {page_num + 1}: {e}")
continue
await context.close()
return sorted(list(file_links))
def clean_google_url(url: str) -> str | None:
"""Unwrap a Google result URL and reject Google's own navigation links."""
url = url.strip()
parsed = urlparse(url)
hostname = (parsed.hostname or "").lower()
is_google_host = hostname == "google.com" or hostname.endswith(".google.com")
# Parameter order is unstable. Google may put tracking fields before url=.
if parsed.path == "/url" and (is_google_host or not hostname):
params = parse_qs(parsed.query)
target = next(
(
value
for param in ("url", "q")
for value in params.get(param, [])
if value.startswith(("http://", "https://"))
),
None,
)
if not target:
return None
url = target
parsed = urlparse(url)
hostname = (parsed.hostname or "").lower()
is_google_host = hostname == "google.com" or hostname.endswith(".google.com")
if parsed.scheme not in {"http", "https"} or not hostname or is_google_host:
return None
# Remove marketing trackers while preserving functional download parameters.
query = urlencode(
[
(name, value)
for name, value in parse_qsl(parsed.query, keep_blank_values=True)
if not is_tracking_parameter(name)
],
doseq=True,
)
# Preserve percent-encoding; unquoting can introduce spaces/reserved characters.
# Text-highlight fragments point to the same downloadable file and otherwise
# create duplicate entries in the output.
return parsed._replace(query=query, fragment="").geturl()
def is_tracking_parameter(name: str) -> bool:
name = name.lower()
return name.startswith("utm_") or name in {
"dclid",
"fbclid",
"gclid",
"gbraid",
"msclkid",
"wbraid",
}
def extract_query_filetypes(query: str) -> set[str]:
return {
match.lower()
for match in re.findall(r"\bfiletype:([a-z0-9]{2,5})\b", query, re.IGNORECASE)
}
def is_labeled_file_result(result_text: str, query_filetypes: set[str]) -> bool:
#Detect Google result cards that show a visible file type label
if not query_filetypes:
return False
text = result_text.lower()
for filetype in query_filetypes:
# Google file badges appear as a short standalone thing nex to the file link:
# PDF, OFFICE-X, etc. Require token boundaries to avoid matching prose.
if re.search(rf"(^|[^a-z0-9]){re.escape(filetype)}([^a-z0-9]|$)", text):
return True
return False
def format_size(bytes_size: float) -> str:
# Convert bytes to human-readable format
for unit in ["B", "KB", "MB", "GB", "TB"]:
if bytes_size < 1024.0:
return f"{bytes_size:.2f} {unit}"
bytes_size /= 1024.0
return f"{bytes_size:.2f} PB"
def sanitize_filename(filename: str) -> str:
# Sanitize filename for Windows/Unix compatibility + replaces shits
# Windows forbidden characters: < > : " / \ | ? *
invalid_chars = '<>:"|?*'
for char in invalid_chars:
filename = filename.replace(char, "_")
# Replace forward/back slashes with underscores
filename = filename.replace("/", "_").replace("\\", "_")
# Remove control characters (ASCII 0-31)
filename = "".join(char for char in filename if ord(char) >= 32)
# Trim whitespace and dots from start/end
filename = filename.strip(". ")
# Ensure filename is not empty
if not filename:
filename = "file"
# Windows reserved names
reserved_names = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"COM2",
"COM3",
"COM4",
"COM5",
"COM6",
"COM7",
"COM8",
"COM9",
"LPT1",
"LPT2",
"LPT3",
"LPT4",
"LPT5",
"LPT6",
"LPT7",
"LPT8",
"LPT9",
]
name_without_ext = os.path.splitext(filename)[0].upper()
if name_without_ext in reserved_names:
filename = "_" + filename
return filename
def is_file_link(url: str) -> bool:
"""Determine if a URL points to a file based on its extension."""
url_lower = url.lower()
parsed = urlparse(url_lower)
path = parsed.path
# Skip empty paths or paths that end with /
if not path or path.endswith("/"):
return False
# Check if path has a file extension pattern: .xxx at the end or before ? or #
# Match extensions like .pdf, .docx, .tar.gz, etc.
# Pattern matches: filename ending with .extension (2-5 chars after the last dot)
pattern = r"\.[a-z0-9]{2,5}$"
# Check if path ends with an extension
if re.search(pattern, path):
return True
# Also check the full URL in case extension is before query params or fragments
# e.g., /file.pdf?download=true
if re.search(r"\.[a-z0-9]{2,5}[?#]", url_lower):
return True
return False
def save_links(links: list, output_file: str):
with open(output_file, "w", encoding="utf-8") as f:
for link in links:
f.write(f"{link}\n")
print(f"\nSaved {len(links)} links to {output_file}")
def download_with_flaresolverr(url: str, flaresolverr_url: str, headers: dict = None, timeout: int = 60):
"""Download a file using FlareSolverr to bypass Cloudflare challenges."""
try:
# Step 1: Use FlareSolverr to solve Cloudflare challenge
payload = {
"cmd": "request.get",
"url": url,
"maxTimeout": timeout * 1000, # Convert to milliseconds
}
headers = {"Content-Type": "application/json"}
flaresolverr_response = requests.post(
f"{flaresolverr_url}/v1",
headers=headers,
json=payload,
timeout=timeout + 10
)
flaresolverr_response.raise_for_status()
result = flaresolverr_response.json()
if result.get("status") == "ok":
solution = result.get("solution", {})
# Extract cookies and user agent from FlareSolverr response
cookies_list = solution.get("cookies", [])
user_agent = solution.get("userAgent", "")
# Convert cookies list to dict for requests
cookies = {cookie["name"]: cookie["value"] for cookie in cookies_list}
download_headers = {
"User-Agent": user_agent
}
if headers:
download_headers.update(headers)
actual_response = requests.get(
url,
headers=download_headers,
cookies=cookies,
stream=True,
timeout=timeout
)
actual_response.raise_for_status()
return actual_response
else:
print(f"FlareSolverr error: {result.get('message', 'Unknown error')}")
return None
except Exception as e:
print(f"FlareSolverr request failed: {e}")
return None
def download_files(input_file: str, output_dir: str, proxy: str | None = None, flaresolverr_url: str | None = None):
# Create output directory
Path(output_dir).mkdir(parents=True, exist_ok=True)
# Read URLs from file
try:
with open(input_file, "r", encoding="utf-8") as f:
urls = [line.strip() for line in f if line.strip()]
except FileNotFoundError:
print(f"Error: File '{input_file}' not found.")
return
if not urls:
print(f"No URLs found in {input_file}")
return
print(f"Found {len(urls)} URLs to download")
print(f"Saving to directory: {output_dir}")
# Setup proxy configuration
proxies = None
if proxy:
proxies = {
'http': proxy,
'https': proxy
}
print(f"Using proxy: {proxy}")
if flaresolverr_url:
print(f"Using FlareSolverr: {flaresolverr_url}")
success_count = 0
failed_count = 0
total_bytes = 0
file_types = {}
import time
start_time = time.time()
# Progress bar for overall download progress
print() # Space for individual file progress bar above
pbar_overall = tqdm(
total=len(urls),
desc="Overall Progress",
unit=" file",
position=1,
bar_format="{l_bar}{bar:40}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
colour="green",
ncols=100,
leave=False, # Don't leave the progress bar after completion
)
try:
for idx, url in enumerate(urls, 1):
filename = None
try:
# Download file with progress bar
# Use FlareSolverr if configured, otherwise use regular requests (with proxy if configured)
if flaresolverr_url:
response = download_with_flaresolverr(url, flaresolverr_url)
if response is None:
raise requests.RequestException("FlareSolverr download failed")
else:
response = requests.get(url, timeout=30, stream=True, proxies=proxies)
response.raise_for_status()
# Determine filename from Content-Disposition header if available
content_disposition = response.headers.get("Content-Disposition", "")
if content_disposition:
# Try to extract filename from Content-Disposition header
# RFC 5987 encoded filename (filename*=UTF-8''...) << Seems OK
filename_match = re.search(
r"filename\*=UTF-8''([^;]+)", content_disposition
)
if filename_match:
filename = unquote(filename_match.group(1), encoding="utf-8")
else:
# Try regular filename parameter
filename_match = re.search(
r'filename=["\'"]?([^"\'";]+)', content_disposition
)
if filename_match:
# Try to decode if it looks like it's UTF-8 encoded
raw_filename = filename_match.group(1).strip("\"'")
try:
# If the filename is Latin-1 encoded but contains UTF-8 bytes
filename = raw_filename.encode("latin-1").decode(
"utf-8"
)
except (UnicodeDecodeError, UnicodeEncodeError):
filename = raw_filename
# If no filename from headers, extract from URL path
if not filename:
parsed = urlparse(url)
# URL-decode the path properly
filename = unquote(os.path.basename(parsed.path), encoding="utf-8")
# Determine correct file extension from Content-Type header
content_type = (
response.headers.get("Content-Type", "")
.split(";")[0]
.strip()
.lower()
)
# Map common MIME types to extensions
mime_to_ext = {
"application/pdf": ".pdf",
"application/msword": ".doc",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx",
"application/vnd.ms-excel": ".xls",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx",
"application/vnd.ms-powerpoint": ".ppt",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": ".pptx",
"application/zip": ".zip",
"application/x-zip-compressed": ".zip",
"text/plain": ".txt",
"text/csv": ".csv",
"image/jpeg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
}
# Get extension from content-type if available
correct_ext = mime_to_ext.get(content_type, "")
# If we have a filename but it has wrong extension (e.g., .aspx for a PDF)
if filename and correct_ext:
current_ext = os.path.splitext(filename)[1].lower()
# Replace extension if current one doesn't match content type
if current_ext != correct_ext and current_ext in [
".aspx",
".php",
".jsp",
".cgi",
".asp",
]:
base = os.path.splitext(filename)[0]
filename = f"{base}{correct_ext}"
# If still no filename, generate one
if not filename or "." not in filename:
ext = correct_ext if correct_ext else ""
filename = f"file_{idx}{ext}"
# Sanitize filename for filesystem compatibility
filename = sanitize_filename(filename)
output_path = os.path.join(output_dir, filename)
# Handle duplicate filenames
if os.path.exists(output_path):
base, ext = os.path.splitext(filename)
counter = 1
while os.path.exists(output_path):
filename = f"{base}_{counter}{ext}"
output_path = os.path.join(output_dir, filename)
counter += 1
# Get file size from headers if available
total_size = int(response.headers.get("content-length", 0))
# Progress bar for individual file download
desc = f"Downloading {filename[:35]}"
with tqdm(
total=total_size,
desc=desc,
unit="B",
unit_scale=True,
unit_divisor=1024,
position=0,
leave=False,
bar_format="{desc}: {percentage:3.0f}%|{bar:30}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}, {rate_fmt}]",
colour="cyan",
ncols=100,
) as pbar_file:
downloaded_size = 0
mode = "wb"
max_retries = 5
retry_count = 0
while True:
try:
with open(output_path, mode) as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
downloaded_size += len(chunk)
pbar_file.update(len(chunk))
# Check if download has full file (some servers might have problems with content length)
if total_size > 0 and downloaded_size < total_size:
raise requests.exceptions.ChunkedEncodingError(f"Incomplete read: got {downloaded_size} of {total_size} bytes")
break # success
except requests.RequestException as e:
retry_count += 1
if retry_count > max_retries:
raise # max retries exceeded
if total_size == 0 and downloaded_size > 0:
raise
# short pause before retry (1 or 2 seconds sould be OK-ish)
time.sleep(2)
# resume
resume_headers = {"Range": f"bytes={downloaded_size}-"}
mode = "ab" # append to the existing file
if flaresolverr_url:
response = download_with_flaresolverr(url, flaresolverr_url, headers=resume_headers)
if response is None:
raise requests.RequestException("FlareSolverr resume download failed")
else:
response = requests.get(url, headers=resume_headers, timeout=30, stream=True, proxies=proxies)
response.raise_for_status()
file_size = os.path.getsize(output_path)
total_bytes += file_size
# Track file type
ext = os.path.splitext(filename)[1].lower()
if ext:
file_types[ext] = file_types.get(ext, 0) + 1
# Format output with padding for alignment
pbar_overall.write(
f" ✓ {filename:<50s} {format_size(file_size):>10s}"
)
success_count += 1
except requests.RequestException as e:
display_name = filename if filename else url[:50]
pbar_overall.write(f" ✗ {display_name:<50s} FAILED")
failed_count += 1
except Exception as e:
display_name = filename if filename else url[:50]
pbar_overall.write(f" ✗ {display_name:<50s} ERROR")
failed_count += 1
finally:
pbar_overall.update(1)
finally:
# Close the progress bar - it will auto-clear because leave=False
pbar_overall.close()
# Add a newline for spacing
print()
# Calculate statistics
end_time = time.time()
elapsed_time = end_time - start_time
avg_speed = total_bytes / elapsed_time if elapsed_time > 0 else 0
# Display statistics
print(f"{'='*80}")
print(f"{'DOWNLOAD STATISTICS':^80}")
print(f"{'='*80}")
print(f" Total files processed: {len(urls)}")
print(f" Successfully downloaded: {success_count}")
print(f" Failed downloads: {failed_count}")
print(f" Total size: {format_size(total_bytes)}")
print(f" Time elapsed: {elapsed_time:.2f}s")
print(f" Average speed: {format_size(avg_speed)}/s")
if file_types:
print(f"\n File types downloaded:")
for ext, count in sorted(file_types.items(), key=lambda x: x[1], reverse=True):
print(f" {ext:10s} : {count:3d} file{'s' if count != 1 else ''}")
print(f"{'='*80}")
async def main():
parser = argparse.ArgumentParser(
description="""
╔═══════════════════════════════════════════════════════════════════════════════╗
║ DORKWRIGHT - Google Dorker ║
║ Extract file links from Google search results and download them ║
╚═══════════════════════════════════════════════════════════════════════════════╝
""",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
═══════════════════════════════════════════════════════════════════════════════════
USAGE EXAMPLES:
Search and save links:
─────────────────────────────────────────────────────────────────────────────
uv run %(prog)s -q "site:example.com filetype:doc OR filetype:docx OR filetype:dot"
uv run %(prog)s -q "site:example.com filetype:pdf" -p 5 -o results.txt
Search and download immediately:
─────────────────────────────────────────────────────────────────────────────
uv run %(prog)s -q "site:example.com filetype:doc" --download --download-dir downloads
Download from existing file:
─────────────────────────────────────────────────────────────────────────────
uv run %(prog)s --input-file file_links.txt --download-dir my_files
Download with proxy or FlareSolverr (for Cloudflare bypass):
─────────────────────────────────────────────────────────────────────────────
uv run %(prog)s --input-file file_links.txt --proxy http://127.0.0.1:8080
uv run %(prog)s --input-file file_links.txt --flaresolverr http://localhost:8191
uv run %(prog)s -q "site:example.com filetype:pdf" --download --flaresolverr http://localhost:8191
═══════════════════════════════════════════════════════════════════════════════════
""",
)
# Search options
parser.add_argument(
"-q",
"--query",
metavar="QUERY",
help='Google search query (e.g., "site:example.com filetype:doc")\n\n',
)
parser.add_argument(
"-p",
"--pages",
metavar="N",
type=int,
default=10,
help="Maximum number of result pages to scrape (default: 10)\n\n",
)
parser.add_argument(
"-d",
"--delay",
metavar="SECONDS",
type=int,
default=3,
help="Delay in seconds between page requests to avoid CAPTCHA (default: 3)\n\n",
)
# Output options
parser.add_argument(
"-o",
"--output",
metavar="FILE",
default="file_links.txt",
help="Output file for extracted links (default: file_links.txt)\n\n",
)
# Download options
parser.add_argument(
"--download",
action="store_true",
help="Download files after extracting links\n\n",
)
parser.add_argument(
"--download-dir",
metavar="DIR",
default="downloads",
help="Directory to save downloaded files (default: downloads)\n\n",
)
parser.add_argument(
"--input-file",
metavar="FILE",
help="Input file with URLs to download (skip search if provided)\n\n",
)
# Proxy options
parser.add_argument(
"--proxy",
metavar="URL",
help="Proxy server URL (e.g., http://127.0.0.1:8080, socks5://127.0.0.1:1080)\n\n",
)
parser.add_argument(
"--flaresolverr",
metavar="URL",
help="FlareSolverr endpoint for bypassing Cloudflare (e.g., http://localhost:8191)\n\n",
)
args = parser.parse_args()
# Mode 1: Download from existing file
if args.input_file:
download_files(args.input_file, args.download_dir, args.proxy, args.flaresolverr)
return
# Mode 2: Search and optionally download
if not args.query:
parser.error(
"the following arguments are required: -q/--query (unless using --input-file)"
)
print(f"Searching Google for: {args.query}")
print(f"Max pages: {args.pages}")
print(f"Delay between pages: {args.delay}s\n")
# Extract links
links = await extract_file_links(
query=args.query, max_pages=args.pages, delay=args.delay
)
# Display results
print(f"\n{'='*60}")
print(f"Found {len(links)} unique file links:")
print(f"{'='*60}")
for link in links:
print(link)
# Save to file
if links:
save_links(links, args.output)
# Download if requested
if args.download:
print(f"\nStarting downloads...\n")
download_files(args.output, args.download_dir, args.proxy, args.flaresolverr)
else:
print(f"\nYou can download all files with:")
print(
f" uv run {parser.prog} --input-file {args.output} --download-dir {args.download_dir}"
)
print(f"Or with wget:")
print(f" wget -i {args.output}")
else:
print("\nNo file links found.")
if __name__ == "__main__":
# Windows redirects stdout using the local code page by default.
if (
sys.platform == "win32"
and not sys.stdout.isatty()
and "PYTHONIOENCODING" not in os.environ
):
sys.stdout.reconfigure(encoding="utf-8")
asyncio.run(main())