-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscreenshot.py
More file actions
175 lines (150 loc) · 4.95 KB
/
Copy pathscreenshot.py
File metadata and controls
175 lines (150 loc) · 4.95 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
import argparse
import io
from pathlib import Path
import time
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
def parse_args():
parser = argparse.ArgumentParser(
description="Capture a screenshot of a URL using Selenium."
)
parser.add_argument(
"url",
nargs="?",
default="https://example.com",
help="Page URL to capture.",
)
parser.add_argument(
"-o",
"--output",
default="screenshots/screenshot.png",
help="Output file path.",
)
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--element",
help="CSS selector for an element screenshot.",
)
output_group.add_argument(
"--full-page",
action="store_true",
help="Scroll and stitch a full-page screenshot.",
)
parser.add_argument(
"--headed",
action="store_true",
help="Run with a visible browser window.",
)
parser.add_argument(
"--width",
type=int,
default=1920,
help="Viewport width.",
)
parser.add_argument(
"--height",
type=int,
default=1080,
help="Viewport height.",
)
parser.add_argument(
"--extra-wait",
type=float,
default=0.0,
help="Extra seconds to wait after the body loads.",
)
parser.add_argument(
"--scroll-wait",
type=float,
default=0.2,
help="Seconds to wait after each scroll when stitching.",
)
return parser.parse_args()
def build_driver(headless, width, height):
options = webdriver.ChromeOptions()
if headless:
options.add_argument("--headless")
options.add_argument(f"--window-size={width},{height}")
options.add_argument("--disable-gpu")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
return webdriver.Chrome(
service=ChromeService(ChromeDriverManager().install()),
options=options,
)
def full_page_screenshot(driver, output_path, scroll_wait):
metrics = driver.execute_script(
"""
const body = document.body;
const html = document.documentElement;
const totalHeight = Math.max(
body.scrollHeight, body.offsetHeight, body.clientHeight,
html.scrollHeight, html.offsetHeight, html.clientHeight
);
const viewportHeight = window.innerHeight;
return { totalHeight, viewportHeight };
"""
)
total_height = int(metrics["totalHeight"])
viewport_height = int(metrics["viewportHeight"])
if viewport_height <= 0:
raise RuntimeError("Viewport height is zero")
last_scroll = max(total_height - viewport_height, 0)
positions = list(range(0, total_height, viewport_height))
if not positions or positions[-1] != last_scroll:
positions.append(last_scroll)
screenshots = []
for offset in positions:
driver.execute_script(
"document.documentElement.scrollTo(0, arguments[0]);"
"document.body.scrollTo(0, arguments[0]);",
offset,
)
time.sleep(scroll_wait)
png = driver.get_screenshot_as_png()
screenshots.append(Image.open(io.BytesIO(png)))
if not screenshots:
raise RuntimeError("No screenshots captured")
scale = screenshots[0].height / viewport_height
total_height_px = int(total_height * scale)
total_width_px = screenshots[0].width
stitched = Image.new("RGB", (total_width_px, total_height_px))
y = 0
for img in screenshots:
remaining = total_height_px - y
if remaining <= 0:
break
if img.height > remaining:
img = img.crop((0, 0, img.width, remaining))
stitched.paste(img, (0, y))
y += img.height
stitched.save(output_path)
def main():
args = parse_args()
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
driver = build_driver(not args.headed, args.width, args.height)
try:
driver.get(args.url)
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
if args.extra_wait > 0:
time.sleep(args.extra_wait)
if args.full_page:
full_page_screenshot(driver, str(output_path), args.scroll_wait)
elif args.element:
element = driver.find_element(By.CSS_SELECTOR, args.element)
element.screenshot(str(output_path))
else:
driver.save_screenshot(str(output_path))
finally:
driver.quit()
print(f"Saved screenshot to {output_path}")
if __name__ == "__main__":
main()