-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspeed_analysis.py
More file actions
341 lines (291 loc) · 11.7 KB
/
Copy pathspeed_analysis.py
File metadata and controls
341 lines (291 loc) · 11.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
#!/usr/bin/env python3
"""Minimal Selenium-only speed analysis.
This lightweight script navigates to a URL with Selenium and queries
the Performance API to return FCP, LCP and an estimated TBT.
"""
import argparse
import sys
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
def human(ms):
if ms is None:
return "n/a"
try:
ms = float(ms)
except Exception:
return "n/a"
if ms >= 1000:
return f"{ms/1000:.2f} s"
return f"{ms:.0f} ms"
def run(url, chrome_path=None, wait=5):
opts = Options()
opts.add_argument("--headless=new")
opts.add_argument("--no-sandbox")
opts.add_argument("--disable-dev-shm-usage")
if chrome_path:
opts.binary_location = chrome_path
driver = webdriver.Chrome(options=opts)
try:
driver.set_page_load_timeout(wait + 30)
t0 = time.time()
driver.get(url)
t1 = time.time()
time.sleep(wait)
total_load_time = (t1 - t0) * 1000.0
js = r"""
(function(){
var r={fcp:null,lcp:null,longTasks:[]};
try{ (performance.getEntriesByType||(()=>[]))('paint').forEach(function(e){ if(e.name==='first-contentful-paint') r.fcp=e.startTime; }); }catch(e){}
try{ (performance.getEntriesByType||(()=>[]))('largest-contentful-paint').forEach(function(e){ r.lcp=e.startTime||e.renderTime||r.lcp; }); }catch(e){}
try{
if(window.PerformanceObserver){
var obs = new PerformanceObserver(function(list){ list.getEntries().forEach(function(e){ if(e.entryType==='longtask') r.longTasks.push(e.duration); }); });
try{ obs.observe({type:'longtask', buffered:true}); }catch(e){}
} else {
(performance.getEntriesByType||(()=>[]))('longtask').forEach(function(e){ r.longTasks.push(e.duration); });
}
}catch(e){}
return r;
})();
"""
res = driver.execute_script(js) or {}
long_tasks = res.get('longTasks') or []
tbt = None
if long_tasks:
try:
tbt = sum(max(0, float(d)-50.0) for d in long_tasks)
except Exception:
tbt = None
print('\nSpeed Analysis Report')
print('---------------------')
print('First Contentful Paint:', human(res.get('fcp')))
print('Largest Contentful Paint:', human(res.get('lcp')))
print('Total Blocking Time (approx):', human(tbt))
finally:
try:
driver.quit()
except Exception:
pass
def main():
p = argparse.ArgumentParser()
p.add_argument('url')
p.add_argument('--chrome-path')
p.add_argument('--wait', type=int, default=5)
args = p.parse_args()
try:
run(args.url, chrome_path=args.chrome_path, wait=args.wait)
except Exception as e:
print('Error:', e, file=sys.stderr)
sys.exit(2)
if __name__ == '__main__':
main()
#!/usr/bin/env python3
"""Website speed analysis (Selenium default, optional Lighthouse).
Collects FCP, LCP and estimates TBT. Defaults to Selenium; pass
`--use-lighthouse` to run Lighthouse via `npx` if available.
"""
import argparse
import json
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
try:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
except Exception:
webdriver = None
def human(ms: float) -> str:
if ms is None:
return "n/a"
try:
ms = float(ms)
except Exception:
return "n/a"
if ms >= 1000:
return f"{ms/1000:.2f} s"
return f"{ms:.0f} ms"
def evaluate_score(score: float) -> str:
if score is None:
return "n/a"
try:
s = float(score)
except Exception:
return "n/a"
if s >= 0.9:
return "Good"
if s >= 0.5:
return "Needs Improvement"
return "Poor"
def run_lighthouse(url: str, chrome_path: str = None, timeout: int = 120):
npx = shutil.which("npx")
if not npx:
raise FileNotFoundError("npx not found on PATH; install Node.js and npm")
with tempfile.NamedTemporaryFile(suffix=".report.json", delete=False) as tmp:
out_path = tmp.name
cmd = [
npx,
"lighthouse",
url,
"--quiet",
"--output=json",
f"--output-path={out_path}",
"--only-categories=performance",
"--chrome-flags=--headless --no-sandbox --disable-gpu",
]
if chrome_path:
cmd.append(f"--chrome-path={chrome_path}")
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, timeout=timeout)
if proc.returncode != 0:
raise RuntimeError(f"Lighthouse failed: {proc.stderr.strip()[:1000]}")
data = json.loads(Path(out_path).read_text())
def get(name):
try:
return data["audits"][name]["numericValue"]
except Exception:
return None
metrics = {
"first-contentful-paint": get("first-contentful-paint"),
"largest-contentful-paint": get("largest-contentful-paint"),
"total-blocking-time": get("total-blocking-time"),
"speed-index": get("speed-index"),
"performance_score": data.get("categories", {}).get("performance", {}).get("score"),
}
return metrics
def selenium_fallback(url: str, headless: bool = True, wait: int = 8, chrome_path: str = None):
if webdriver is None:
raise RuntimeError("Selenium not installed in this environment")
opts = Options()
if headless:
opts.add_argument("--headless=new")
opts.add_argument("--no-sandbox")
opts.add_argument("--disable-dev-shm-usage")
if chrome_path:
opts.binary_location = chrome_path
driver = webdriver.Chrome(options=opts)
try:
# Install a script to run on every new document to capture performance entries
js_observer = r"""
(function(){
try{ if(window.__speedResults) return; }catch(e){}
(function(){
try{ if(window.__speedResults) return; }catch(e){}
var results = {fcp:null, lcp:null, longTasks:[]};
try{
if(window.PerformanceObserver){
var obs = new PerformanceObserver(function(list){
list.getEntries().forEach(function(e){
try{
if(e.entryType==='longtask') results.longTasks.push(e.duration);
if(e.entryType==='largest-contentful-paint') results.lcp = e.startTime || e.renderTime || results.lcp;
if(e.entryType==='paint' && e.name==='first-contentful-paint') results.fcp = e.startTime;
}catch(_){ }
});
});
try{ obs.observe({type:'longtask', buffered:true}); }catch(_){ }
try{ obs.observe({type:'largest-contentful-paint', buffered:true}); }catch(_){ }
try{ obs.observe({type:'paint', buffered:true}); }catch(_){ }
} else {
var paints = performance.getEntriesByType && performance.getEntriesByType('paint') || [];
for(var i=0;i<paints.length;i++){ if(paints[i].name==='first-contentful-paint') results.fcp = paints[i].startTime; }
var lcps = performance.getEntriesByType && performance.getEntriesByType('largest-contentful-paint') || [];
if(lcps.length) results.lcp = lcps[lcps.length-1].startTime || lcps[lcps.length-1].renderTime || results.lcp;
var lts = performance.getEntriesByType && performance.getEntriesByType('longtask') || [];
for(var j=0;j<lts.length;j++) results.longTasks.push(lts[j].duration);
}
}catch(_){ }
try{ window.__speedResults = results; }catch(_){ }
})();
})();
"""
try:
driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': js_observer})
except Exception:
# older selenium / drivers may not support CDP; continue without injection
pass
driver.set_page_load_timeout(wait + 30)
t0 = time.time()
driver.get(url)
t1 = time.time()
time.sleep(wait)
total_load_time = (t1 - t0) * 1000.0
# Try to read results populated by the injected observer first
try:
results = driver.execute_script('return window.__speedResults') or {}
except Exception:
results = {}
# Fallback: try to collect entries post-load if observer didn't populate
if not results:
js = r"""
(function(){
var r={fcp:null,lcp:null,longTasks:[]};
try{ (performance.getEntriesByType||(()=>[]))('paint').forEach(function(e){ if(e.name==='first-contentful-paint') r.fcp=e.startTime; }); }catch(e){}
try{ (performance.getEntriesByType||(()=>[]))('largest-contentful-paint').forEach(function(e){ r.lcp=e.startTime||e.renderTime||r.lcp; }); }catch(e){}
try{ (performance.getEntriesByType||(()=>[]))('longtask').forEach(function(e){ r.longTasks.push(e.duration); }); }catch(e){}
return r;
})();
"""
try:
results = driver.execute_script(js) or {}
except Exception:
results = {}
long_tasks = results.get('longTasks') or []
tbt = None
if long_tasks:
try:
tbt = sum(max(0, float(d)-50.0) for d in long_tasks)
except Exception:
tbt = None
metrics = {
"first-contentful-paint": results.get('fcp') if isinstance(results.get('fcp'), (int, float)) else None,
"largest-contentful-paint": results.get('lcp') if isinstance(results.get('lcp'), (int, float)) else None,
"total-blocking-time": tbt,
"total_load_time": total_load_time,
"speed-index": None,
"performance_score": None,
}
return metrics
finally:
try:
driver.quit()
except Exception:
pass
def print_report(metrics: dict):
fcp = metrics.get("first-contentful-paint")
lcp = metrics.get("largest-contentful-paint")
tbt = metrics.get("total-blocking-time")
total_load_time = metrics.get("total_load_time")
si = metrics.get("speed-index")
score = metrics.get("performance_score")
print("\nSpeed Analysis Report")
print("---------------------")
print(f"First Contentful Paint: {human(fcp)}")
print(f"Largest Contentful Paint: {human(lcp)}")
print(f"Total Blocking Time (approx): {human(tbt)}")
print(f"Total load time: {human(total_load_time)}")
print(f"Speed Index: {human(si)}")
if score is not None:
print(f"Performance score: {score*100:.0f}/100 — {evaluate_score(score)}")
else:
print("Performance score: n/a")
def main():
p = argparse.ArgumentParser(description="Website speed analysis (Lighthouse + Selenium fallback)")
p.add_argument("url")
p.add_argument("--chrome-path", help="Path to Chrome/Chromium binary")
p.add_argument("--use-lighthouse", action="store_true", help="Use Lighthouse via npx instead of Selenium (default: Selenium)")
p.add_argument("--wait", type=int, default=5, help="Seconds to wait after load when using Selenium")
args = p.parse_args()
try:
if args.use_lighthouse:
metrics = run_lighthouse(args.url, chrome_path=args.chrome_path)
else:
metrics = selenium_fallback(args.url, wait=args.wait, chrome_path=args.chrome_path)
print_report(metrics)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(2)
if __name__ == "__main__":
main()