"""Coimbatore web design company speed study. Loads each homepage in headless Chrome as a mid-range phone on a slow 4G connection (Lighthouse's mobile profile: 150 ms RTT, 1.6 Mbps down, 750 kbps up, 4x CPU slowdown), cold cache, N runs per site, and records LCP, FCP, CLS, load time, bytes transferred, request and script counts. usage: python3 measure.py sites.txt out.jsonl [runs] """ import json, statistics, sys, time from playwright.sync_api import sync_playwright UA = ("Mozilla/5.0 (Linux; Android 11; moto g power (2022)) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36") OBSERVE = """ window.__m = {lcp: 0, cls: 0, fcp: 0}; new PerformanceObserver(l => { for (const e of l.getEntries()) window.__m.lcp = e.startTime; }) .observe({type: 'largest-contentful-paint', buffered: true}); new PerformanceObserver(l => { for (const e of l.getEntries()) if (!e.hadRecentInput) window.__m.cls += e.value; }) .observe({type: 'layout-shift', buffered: true}); new PerformanceObserver(l => { for (const e of l.getEntries()) if (e.name === 'first-contentful-paint') window.__m.fcp = e.startTime; }) .observe({type: 'paint', buffered: true}); """ CHALLENGE = ("checking your browser", "just a moment", "attention required", "verify you are human") CTX = dict(viewport={"width": 412, "height": 823}, device_scale_factor=1.75, is_mobile=True, has_touch=True, user_agent=UA, ignore_https_errors=True) def pass_challenge(browser, url): """Bot-check pages (Hostinger, Cloudflare) are not the site. Clear one in a throwaway context and return its cookies; the measured run then starts in a fresh context.""" ctx = browser.new_context(**CTX) page = ctx.new_page() state, challenged = None, False try: page.goto(url, wait_until="load", timeout=120_000) for _ in range(20): if not any(c in page.title().lower() for c in CHALLENGE): break challenged = True page.wait_for_timeout(1500) if challenged: page.wait_for_load_state("load", timeout=60_000) state = ctx.storage_state() except Exception: pass ctx.close() return state, challenged def run_once(browser, url, state=None): ctx = browser.new_context(**CTX, storage_state=state) ctx.add_init_script(OBSERVE) page = ctx.new_page() cdp = ctx.new_cdp_session(page) cdp.send("Network.enable") cdp.send("Network.setCacheDisabled", {"cacheDisabled": True}) cdp.send("Network.emulateNetworkConditions", {"offline": False, "latency": 150, "downloadThroughput": 1.6 * 1024 * 1024 / 8, "uploadThroughput": 750 * 1024 / 8}) cdp.send("Emulation.setCPUThrottlingRate", {"rate": 4}) st = {"bytes": 0, "requests": 0, "js_bytes": 0, "scripts": 0, "types": {}} cdp.on("Network.requestWillBeSent", lambda e: st.__setitem__("requests", st["requests"] + 1)) cdp.on("Network.responseReceived", lambda e: st["types"].__setitem__(e["requestId"], e.get("type"))) def done(e): st["bytes"] += e.get("encodedDataLength", 0) if st["types"].get(e["requestId"]) == "Script": st["js_bytes"] += e.get("encodedDataLength", 0) st["scripts"] += 1 cdp.on("Network.loadingFinished", done) t0 = time.time() try: page.goto(url, wait_until="load", timeout=120_000) try: page.wait_for_load_state("networkidle", timeout=15_000) except Exception: pass # ponytail: sites with endless polling never go idle; their totals are a floor m = page.evaluate("""() => ({...window.__m, load: performance.getEntriesByType('navigation')[0]?.loadEventEnd || 0, final_url: location.href, title: document.title, coimbatore: /coimbatore/i.test(document.body ? document.body.innerText : '')})""") err = None except Exception as e: m, err = {}, str(e).splitlines()[0][:200] ctx.close() return {"url": url, "wall_s": round(time.time() - t0, 1), "err": err, "bytes": st["bytes"], "requests": st["requests"], "js_bytes": st["js_bytes"], "scripts": st["scripts"], **m} def median(rows, k): v = [r[k] for r in rows if r.get(k) is not None and not r["err"]] return round(statistics.median(v), 3) if v else None def main(): sites, out = sys.argv[1], sys.argv[2] runs = int(sys.argv[3]) if len(sys.argv) > 3 else 3 urls = [l.strip() for l in open(sites) if l.strip() and not l.startswith("#")] with sync_playwright() as p, open(out, "a") as f: browser = p.chromium.launch(executable_path="/usr/bin/google-chrome", args=["--no-sandbox"]) for url in urls: rows = [] state, challenged = pass_challenge(browser, url) for i in range(runs): r = run_once(browser, url, state) if any(c in (r.get("title") or "").lower() for c in CHALLENGE): r["err"] = "bot challenge page, not the site" r["challenged"] = challenged r["run"] = i + 1 r["date"] = time.strftime("%Y-%m-%d") f.write(json.dumps(r) + "\n"); f.flush() rows.append(r) print(url, {k: median(rows, k) for k in ("lcp", "fcp", "cls", "load", "bytes", "requests", "js_bytes", "scripts")}, "errors:", sum(1 for r in rows if r["err"]), flush=True) browser.close() if __name__ == "__main__": main()