mucahitkantepe commited on
Commit
c657278
·
1 Parent(s): 930ed2b

add Massimo Dutti scraper

Browse files

Inditex itxrest API behind Akamai. Playwright + playwright-stealth
warms the cookie jar, then ctx.request.get() calls the JSON endpoints.
~30 product/category, 11 women categories, Norway market.

- taste/scrapers/api/massimodutti.py (new): scraper, schema mapping
- taste/scrapers/__init__.py: register
- taste/config.py: add to default config
- pyproject.toml: bump browser extra to include playwright-stealth

.scratch/spike.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Massimo Dutti Akamai bypass spike — Playwright cookie warmer + JSON API."""
2
+ import json
3
+ import sys
4
+ from playwright.sync_api import sync_playwright
5
+
6
+
7
+ HOME = "https://www.massimodutti.com/no/en/"
8
+ STORE_ID = 34009477
9
+ # catalog 40259534 was extracted from rest service hints earlier; confirm via response.
10
+ CATALOG_ID = 40259534
11
+ # probe with categoryId=0 (root) — list everything in the catalog
12
+ API = f"https://www.massimodutti.com/itxrest/2/catalog/store/{STORE_ID}/{CATALOG_ID}/category/0/product?languageId=-1"
13
+
14
+
15
+ def main() -> int:
16
+ with sync_playwright() as pw:
17
+ browser = pw.chromium.launch(headless=True, args=["--disable-blink-features=AutomationControlled"])
18
+ ctx = browser.new_context(
19
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
20
+ locale="en-US",
21
+ viewport={"width": 1280, "height": 800},
22
+ )
23
+ # Strip the navigator.webdriver tell.
24
+ ctx.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
25
+ page = ctx.new_page()
26
+ print(f" -> navigating {HOME}", flush=True)
27
+ page.goto(HOME, wait_until="domcontentloaded", timeout=30000)
28
+ print(f" -> waiting for Akamai challenge to settle", flush=True)
29
+ page.wait_for_timeout(5000)
30
+ cookies = ctx.cookies()
31
+ akamai = [c["name"] for c in cookies if c["name"].startswith(("_abck", "bm_"))]
32
+ print(f" cookies: {len(cookies)} total, akamai={akamai}", flush=True)
33
+
34
+ print(f" -> calling API: {API}", flush=True)
35
+ resp = page.request.get(API, headers={
36
+ "Accept": "application/json",
37
+ "Referer": HOME,
38
+ "Accept-Language": "en-US,en;q=0.9",
39
+ })
40
+ print(f" status={resp.status} content-type={resp.headers.get('content-type', '?')}", flush=True)
41
+ body = resp.body()
42
+ print(f" body size: {len(body)}B", flush=True)
43
+ if resp.status == 200 and len(body) > 200:
44
+ try:
45
+ data = json.loads(body)
46
+ if isinstance(data, dict):
47
+ keys = list(data.keys())
48
+ print(f" json keys: {keys[:10]}", flush=True)
49
+ if "productIds" in data:
50
+ print(f" productIds: {len(data['productIds'])} items", flush=True)
51
+ if "products" in data and data["products"]:
52
+ sample = data["products"][0]
53
+ print(f" sample product keys: {list(sample.keys())[:15]}", flush=True)
54
+ print(f" sample: {json.dumps(sample, indent=2)[:1500]}", flush=True)
55
+ else:
56
+ print(f" json type: {type(data).__name__}, len={len(data)}", flush=True)
57
+ except Exception as e:
58
+ print(f" json parse failed: {e}", flush=True)
59
+ print(f" body[:300]: {body[:300]!r}", flush=True)
60
+ else:
61
+ print(f" body[:300]: {body[:300]!r}", flush=True)
62
+ browser.close()
63
+ return 0
64
+
65
+
66
+ if __name__ == "__main__":
67
+ sys.exit(main())
.scratch/spike2.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Probe API versions + category IDs after warming cookies."""
2
+ import json
3
+ from playwright.sync_api import sync_playwright
4
+
5
+ HOME = "https://www.massimodutti.com/no/en/"
6
+ DRESSES_PAGE = "https://www.massimodutti.com/no/en/women/dresses-n1494"
7
+ STORE_ID = 34009477
8
+
9
+ with sync_playwright() as pw:
10
+ browser = pw.chromium.launch(headless=True, args=["--disable-blink-features=AutomationControlled"])
11
+ ctx = browser.new_context(
12
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
13
+ locale="en-US",
14
+ viewport={"width": 1280, "height": 800},
15
+ )
16
+ ctx.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
17
+ page = ctx.new_page()
18
+
19
+ # warm cookies on home + dresses category page
20
+ page.goto(HOME, wait_until="domcontentloaded", timeout=30000)
21
+ page.wait_for_timeout(3000)
22
+ print(f"home cookies: {len(ctx.cookies())}")
23
+ page.goto(DRESSES_PAGE, wait_until="domcontentloaded", timeout=30000)
24
+ page.wait_for_timeout(5000)
25
+ print(f"after dresses: {len(ctx.cookies())} cookies, akamai_present={any(c['name'].startswith(('_abck','bm_')) for c in ctx.cookies())}")
26
+
27
+ # let's see all XHRs the dresses page made (productIds endpoint)
28
+ xhrs = []
29
+ page.on("request", lambda r: xhrs.append((r.method, r.url)) if "itxrest" in r.url else None)
30
+ page.reload(wait_until="domcontentloaded")
31
+ page.wait_for_timeout(8000)
32
+ print(f"\nitxrest XHRs from dresses page (sampled): {len(xhrs)}")
33
+ for m, u in xhrs[:15]:
34
+ print(f" {m} {u[:140]}")
35
+
36
+ # probe several endpoint shapes
37
+ base_headers = {
38
+ "Accept": "application/json",
39
+ "Referer": DRESSES_PAGE,
40
+ "Accept-Language": "en-US,en;q=0.9",
41
+ }
42
+ endpoints = [
43
+ f"https://www.massimodutti.com/itxrest/3/catalog/store/{STORE_ID}/40259534/category/1494/product?languageId=-1",
44
+ f"https://www.massimodutti.com/itxrest/3/catalog/store/{STORE_ID}/category",
45
+ f"https://www.massimodutti.com/itxrest/4/catalog/store/{STORE_ID}/category",
46
+ f"https://www.massimodutti.com/itxrest/2/catalog/store/{STORE_ID}/category",
47
+ ]
48
+ for url in endpoints:
49
+ r = page.request.get(url, headers=base_headers)
50
+ snippet = r.body()[:180] if r.status != 200 else b""
51
+ print(f"\n {r.status} {url[40:]}")
52
+ print(f" body[:180]={snippet!r}")
53
+ if r.status == 200:
54
+ try:
55
+ data = json.loads(r.body())
56
+ if isinstance(data, dict):
57
+ print(f" keys={list(data.keys())[:10]}")
58
+ elif isinstance(data, list):
59
+ print(f" list len={len(data)}, first keys={list(data[0].keys())[:10] if data else '<empty>'}")
60
+ except Exception as e:
61
+ print(f" parse err: {e}")
62
+ browser.close()
.scratch/spike3.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inspect rendered HTML on a category page — look for embedded product JSON."""
2
+ import json
3
+ import re
4
+ from playwright.sync_api import sync_playwright
5
+
6
+ DRESSES = "https://www.massimodutti.com/no/en/women/dresses-n1494"
7
+
8
+ with sync_playwright() as pw:
9
+ browser = pw.chromium.launch(headless=True, args=["--disable-blink-features=AutomationControlled"])
10
+ ctx = browser.new_context(
11
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
12
+ locale="en-US",
13
+ viewport={"width": 1280, "height": 800},
14
+ )
15
+ ctx.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
16
+ page = ctx.new_page()
17
+
18
+ # log every request the page makes
19
+ seen_urls = []
20
+ page.on("request", lambda r: seen_urls.append((r.method, r.url)))
21
+
22
+ page.goto(DRESSES, wait_until="networkidle", timeout=30000)
23
+ page.wait_for_timeout(5000)
24
+ html = page.content()
25
+ print(f"final HTML size: {len(html)}")
26
+ print(f"final URL: {page.url}")
27
+ print(f"total requests: {len(seen_urls)}")
28
+
29
+ # look for itxrest XHRs that might have product data
30
+ api_calls = [u for m, u in seen_urls if "itxrest" in u or "api" in u.lower() or "category" in u.lower()]
31
+ print(f"\napi-ish requests ({len(api_calls)}):")
32
+ for u in api_calls[:25]:
33
+ print(f" {u[:160]}")
34
+
35
+ # search HTML for embedded product JSON
36
+ for marker in ["__NEXT_DATA__", "__INITIAL_STATE__", "window.products", "window.app", "data-products", "window.__"]:
37
+ if marker in html:
38
+ print(f"\nfound marker: {marker}")
39
+ # script tags with JSON
40
+ scripts = re.findall(r'<script[^>]*?type="application/(?:ld\+json|json)"[^>]*>(.*?)</script>', html, re.DOTALL)
41
+ print(f"\nJSON-LD/JSON script tags: {len(scripts)}")
42
+ for s in scripts[:3]:
43
+ print(f" {s[:250]}")
44
+ # bigint product IDs in HTML
45
+ pids = re.findall(r'\bp(\d{6,8})\b', html)
46
+ print(f"\np<digits> patterns: {len(set(pids))} unique, first={list(set(pids))[:10]}")
47
+ # category-* IDs
48
+ cats = re.findall(r'categoryId["\s:=]+(\d{6,8})', html)
49
+ print(f"categoryId numeric: {set(cats)}")
50
+ # find link patterns to product pages
51
+ products = re.findall(r'/no/en/women/[^"]+-l\d+', html)
52
+ print(f"product URLs (-l<digit> pattern): {len(set(products))}, first={list(set(products))[:5]}")
53
+ # save HTML for closer inspection
54
+ open("/tmp/md-rendered.html", "w").write(html)
55
+ print(f"\nsaved -> /tmp/md-rendered.html")
56
+ browser.close()
.scratch/spike4.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Stealth spike: full Chromium + playwright_stealth applied to context."""
2
+ import asyncio
3
+ from playwright.async_api import async_playwright
4
+ from playwright_stealth import Stealth
5
+
6
+ CHROME_PATH = "/Users/mucahitkantepe/Library/Caches/ms-playwright/chromium-1217/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
7
+ HOME = "https://www.massimodutti.com/no/en/"
8
+ DRESSES = "https://www.massimodutti.com/no/en/women/dresses-n1494"
9
+
10
+
11
+ async def main():
12
+ async with Stealth().use_async(async_playwright()) as pw:
13
+ browser = await pw.chromium.launch(
14
+ executable_path=CHROME_PATH,
15
+ headless=True,
16
+ args=[
17
+ "--disable-blink-features=AutomationControlled",
18
+ "--disable-dev-shm-usage",
19
+ "--no-sandbox",
20
+ ],
21
+ )
22
+ ctx = await browser.new_context(
23
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
24
+ locale="en-US",
25
+ timezone_id="Europe/Oslo",
26
+ viewport={"width": 1280, "height": 800},
27
+ extra_http_headers={
28
+ "Accept-Language": "en-US,en;q=0.9,no;q=0.8",
29
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
30
+ "Accept-Encoding": "gzip, deflate, br",
31
+ },
32
+ )
33
+ page = await ctx.new_page()
34
+
35
+ # capture all itxrest XHRs
36
+ xhrs = []
37
+ page.on("response", lambda r: xhrs.append((r.status, r.url)) if "itxrest" in r.url else None)
38
+
39
+ print(f"[1/3] navigating {HOME}", flush=True)
40
+ await page.goto(HOME, wait_until="domcontentloaded", timeout=30000)
41
+ await page.wait_for_timeout(4000)
42
+ print(f" home title='{await page.title()}' cookies={len(await ctx.cookies())}", flush=True)
43
+ ck = await ctx.cookies()
44
+ akamai = [c["name"] for c in ck if c["name"].startswith(("_abck","bm_","ak_"))]
45
+ print(f" akamai cookies: {akamai}", flush=True)
46
+
47
+ print(f"\n[2/3] navigating {DRESSES}", flush=True)
48
+ await page.goto(DRESSES, wait_until="domcontentloaded", timeout=30000)
49
+ await page.wait_for_timeout(7000)
50
+ html = await page.content()
51
+ title = await page.title()
52
+ print(f" title='{title}' html_size={len(html)}", flush=True)
53
+ ck = await ctx.cookies()
54
+ akamai = [c["name"] for c in ck if c["name"].startswith(("_abck","bm_","ak_"))]
55
+ print(f" akamai cookies: {akamai}", flush=True)
56
+
57
+ if "Access Denied" in html or "denied" in title.lower():
58
+ print(f" STILL BLOCKED: title={title!r}", flush=True)
59
+ else:
60
+ # look for product hooks
61
+ import re
62
+ n_links = len(re.findall(r'/no/en/women/[^"]+-l\d+', html))
63
+ n_imgs = len(re.findall(r'static\.massimodutti\.com|static\.zara\.net|/products/.*\.jpg', html))
64
+ n_pids = len(set(re.findall(r'\bp(\d{7})\b', html)))
65
+ print(f" product links: {n_links}, images: {n_imgs}, p<7-digit>: {n_pids}", flush=True)
66
+
67
+ print(f"\n[3/3] itxrest XHRs observed: {len(xhrs)}", flush=True)
68
+ for s, u in xhrs[:10]:
69
+ print(f" {s} {u[:160]}", flush=True)
70
+
71
+ # save HTML
72
+ open("/tmp/md-spike4.html", "w").write(html)
73
+ await browser.close()
74
+
75
+
76
+ asyncio.run(main())
.scratch/spike5.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture API response bodies — get the real product schema."""
2
+ import asyncio
3
+ import json
4
+ from playwright.async_api import async_playwright
5
+ from playwright_stealth import Stealth
6
+
7
+ CHROME_PATH = "/Users/mucahitkantepe/Library/Caches/ms-playwright/chromium-1217/chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
8
+ HOME = "https://www.massimodutti.com/no/en/"
9
+ DRESSES = "https://www.massimodutti.com/no/en/women/dresses-n1494"
10
+
11
+ # (url_substring, save_path)
12
+ TARGETS = [
13
+ ("/category?languageId=", "/tmp/md-cat-tree.json"),
14
+ ("/category/", "/tmp/md-cat-detail.json"),
15
+ ("productsArray", "/tmp/md-products-array.json"),
16
+ ]
17
+
18
+
19
+ async def main():
20
+ saved = {k: False for _, k in TARGETS}
21
+ async with Stealth().use_async(async_playwright()) as pw:
22
+ browser = await pw.chromium.launch(executable_path=CHROME_PATH, headless=True,
23
+ args=["--disable-blink-features=AutomationControlled"])
24
+ ctx = await browser.new_context(
25
+ user_agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36",
26
+ locale="en-US", timezone_id="Europe/Oslo",
27
+ viewport={"width": 1280, "height": 800},
28
+ )
29
+ page = await ctx.new_page()
30
+
31
+ async def on_resp(r):
32
+ if r.status != 200 or "itxrest" not in r.url:
33
+ return
34
+ for sub, path in TARGETS:
35
+ if sub in r.url and not saved[path]:
36
+ try:
37
+ body = await r.body()
38
+ open(path, "wb").write(body)
39
+ saved[path] = True
40
+ print(f" saved {path} size={len(body)} url={r.url[:140]}", flush=True)
41
+ except Exception as e:
42
+ print(f" err saving: {e}", flush=True)
43
+
44
+ page.on("response", on_resp)
45
+
46
+ await page.goto(HOME, wait_until="domcontentloaded", timeout=30000)
47
+ await page.wait_for_timeout(4000)
48
+ await page.goto(DRESSES, wait_until="domcontentloaded", timeout=30000)
49
+ # let the lazy-loading XHRs fire
50
+ await page.wait_for_timeout(8000)
51
+ # scroll to trigger more product loads
52
+ await page.evaluate("window.scrollTo(0, document.body.scrollHeight)")
53
+ await page.wait_for_timeout(5000)
54
+ await browser.close()
55
+ print(f"\nsaved status: {saved}")
56
+
57
+
58
+ asyncio.run(main())
.scratch/test_scraper.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end smoke test: fetch ~20 dresses + ~10 shoes, print structured."""
2
+ import json, sys
3
+ sys.path.insert(0, ".")
4
+
5
+ from taste.config import StoreConfig
6
+ from taste.scrapers.api.massimodutti import MassimoDuttiScraper
7
+
8
+ sc = StoreConfig(name="massimodutti", base_url="https://www.massimodutti.com",
9
+ categories=["dresses", "shoes"], max_products=30)
10
+ scraper = MassimoDuttiScraper(sc)
11
+ print("starting scrape...", flush=True)
12
+ products = scraper.scrape()
13
+ print(f"\nfetched {len(products)} products\n", flush=True)
14
+ if products:
15
+ p = products[0]
16
+ print("--- sample product ---")
17
+ pretty = {k: (v[:120] + "..." if isinstance(v, str) and len(v) > 120 else v) for k, v in p.items()}
18
+ print(json.dumps(pretty, indent=2))
19
+ print()
20
+ cats = sorted({p["category"] for p in products})
21
+ in_stock = sum(1 for p in products if p["in_stock"])
22
+ with_img = sum(1 for p in products if p["image_url"])
23
+ avg_price = sum(p["price_nok"] for p in products) / len(products)
24
+ print(f"cats covered: {cats}")
25
+ print(f"in stock: {in_stock}/{len(products)}")
26
+ print(f"with image: {with_img}/{len(products)}")
27
+ print(f"avg price: NOK {avg_price:.0f}")
pyproject.toml CHANGED
@@ -20,7 +20,7 @@ dependencies = [
20
  ]
21
 
22
  [project.optional-dependencies]
23
- browser = ["playwright>=1.40"]
24
 
25
  [project.scripts]
26
  taste = "cli:main"
 
20
  ]
21
 
22
  [project.optional-dependencies]
23
+ browser = ["playwright>=1.45", "playwright-stealth>=2.0"]
24
 
25
  [project.scripts]
26
  taste = "cli:main"
taste/config.py CHANGED
@@ -276,6 +276,26 @@ def _default_config() -> Config:
276
  ],
277
  max_products=5000,
278
  ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  },
280
  )
281
 
 
276
  ],
277
  max_products=5000,
278
  ),
279
+ "massimodutti": StoreConfig(
280
+ name="massimodutti", type="api",
281
+ base_url="https://www.massimodutti.com",
282
+ # Slugs map to Inditex categoryIds inside
283
+ # taste/scrapers/api/massimodutti.py:_CATEGORY_IDS (Norway women).
284
+ categories=[
285
+ "dresses",
286
+ "knitwear",
287
+ "tops",
288
+ "shirts",
289
+ "tshirts",
290
+ "trousers",
291
+ "jeans",
292
+ "skirts",
293
+ "jackets",
294
+ "shoes",
295
+ "bags",
296
+ ],
297
+ max_products=5000,
298
+ ),
299
  },
300
  )
301
 
taste/scrapers/__init__.py CHANGED
@@ -41,6 +41,9 @@ def _get_api_scraper(sc: StoreConfig):
41
  elif name == "nelly":
42
  from taste.scrapers.api.nelly import NellyScraper
43
  return NellyScraper(sc)
 
 
 
44
  raise ValueError(f"No API scraper for store: {sc.name}")
45
 
46
 
 
41
  elif name == "nelly":
42
  from taste.scrapers.api.nelly import NellyScraper
43
  return NellyScraper(sc)
44
+ elif name == "massimodutti" or name == "massimo dutti":
45
+ from taste.scrapers.api.massimodutti import MassimoDuttiScraper
46
+ return MassimoDuttiScraper(sc)
47
  raise ValueError(f"No API scraper for store: {sc.name}")
48
 
49
 
taste/scrapers/api/massimodutti.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Massimo Dutti scraper — Inditex itxrest API behind Akamai Bot Manager.
2
+
3
+ Massimo Dutti's product API (`/itxrest/3/catalog/...`) returns full structured
4
+ JSON, but the front edge is Akamai-protected and refuses any naïve `httpx.Client`
5
+ request. The fix is a Chromium session warmed with `playwright_stealth`, which
6
+ solves Akamai's JS challenge and gets us the `_abck` / `bm_sz` cookies. After
7
+ warm-up, the same `BrowserContext.request` API is used to call the JSON
8
+ endpoints — the cookies travel automatically and responses come back as plain
9
+ JSON in milliseconds.
10
+
11
+ Pipeline per scrape:
12
+ 1. Launch full Chromium (NOT chromium-headless-shell — too fingerprintable),
13
+ apply stealth patches.
14
+ 2. Navigate the homepage and one category page; wait for Akamai to settle.
15
+ 3. For each women category in `_CATEGORY_IDS`, GET the category endpoint with
16
+ `showProducts=false` to retrieve `productIds[]`.
17
+ 4. Batch the IDs (50 per call) into `productsArray?productIds=...` and parse
18
+ the result.
19
+ 5. Map Inditex's nested schema to the standard product dict the DB expects.
20
+
21
+ Norway market: storeId 34009477, catalogId 30359501. Prices come back as
22
+ integer NOK*100 (i.e. cents); divide by 100. Image URLs live at
23
+ `bundleProductSummaries[0].detail.xmedia[*].xmediaItems[*].medias[*].url`
24
+ on `static.massimodutti.net`.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ from typing import Any
31
+
32
+ from taste.scrapers.base import BaseScraper
33
+
34
+ STORE_ID = 34009477
35
+ CATALOG_ID = 30359501
36
+ BRAND = "Massimo Dutti"
37
+ HOME = "https://www.massimodutti.com/no/en/"
38
+ DRESSES_LANDING = "https://www.massimodutti.com/no/en/women/dresses-n1494"
39
+
40
+ # Map taste-engine canonical slug -> Massimo Dutti VIEW ALL categoryId for the
41
+ # Norway women's collection. Source: walked the /itxrest/2/catalog/.../category
42
+ # tree response (see .scratch/spike5 evidence).
43
+ _CATEGORY_IDS: dict[str, int] = {
44
+ "dresses": 2088776,
45
+ "knitwear": 1925504,
46
+ "tops": 2071730,
47
+ "shirts": 1887041,
48
+ "tshirts": 1982001,
49
+ "trousers": 1887043,
50
+ "jeans": 675012,
51
+ "skirts": 2263547,
52
+ "jackets": 2028560,
53
+ "shoes": 1887045,
54
+ "bags": 1797006,
55
+ }
56
+
57
+ _BATCH = 50 # productsArray accepts ~50 IDs per call before truncating
58
+ _USER_AGENT = (
59
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
60
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
61
+ )
62
+
63
+
64
+ def _resolve_chromium_path() -> str | None:
65
+ """Locate Playwright's full Chromium binary (NOT headless-shell)."""
66
+ import os
67
+ from pathlib import Path
68
+
69
+ env_path = os.environ.get("MD_CHROMIUM_PATH")
70
+ if env_path and Path(env_path).is_file():
71
+ return env_path
72
+
73
+ cache = Path.home() / "Library/Caches/ms-playwright"
74
+ if not cache.is_dir(): # Linux
75
+ cache = Path.home() / ".cache/ms-playwright"
76
+ if not cache.is_dir():
77
+ return None
78
+
79
+ # Pick the highest-numbered chromium-NNNN dir (skip headless-shell).
80
+ candidates = sorted(
81
+ (p for p in cache.glob("chromium-*") if "headless" not in p.name),
82
+ key=lambda p: int(p.name.split("-")[-1]),
83
+ reverse=True,
84
+ )
85
+ for d in candidates:
86
+ for sub in (
87
+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
88
+ "chrome-mac/Chromium.app/Contents/MacOS/Chromium",
89
+ "chrome-linux/chrome",
90
+ ):
91
+ p = d / sub
92
+ if p.is_file():
93
+ return str(p)
94
+ return None
95
+
96
+
97
+ def _api_url(path: str) -> str:
98
+ return f"https://www.massimodutti.com/itxrest/{path}"
99
+
100
+
101
+ def _list_category(api, category_id: int) -> list[int]:
102
+ """Return all productIds visible in a Massimo Dutti category."""
103
+ url = _api_url(
104
+ f"3/catalog/store/{STORE_ID}/{CATALOG_ID}/category/{category_id}/product"
105
+ "?languageId=-1&appId=1&showProducts=false&priceFilter=true"
106
+ )
107
+ resp = api.get(
108
+ url,
109
+ headers={"Accept": "application/json", "Referer": DRESSES_LANDING},
110
+ )
111
+ if resp.status != 200:
112
+ return []
113
+ try:
114
+ data = json.loads(resp.body())
115
+ except Exception:
116
+ return []
117
+ return [int(x) for x in (data.get("productIds") or [])]
118
+
119
+
120
+ def _fetch_products_batch(api, product_ids: list[int]) -> list[dict[str, Any]]:
121
+ """Fetch full product details for up to ~50 IDs in one call."""
122
+ if not product_ids:
123
+ return []
124
+ ids_param = ",".join(str(i) for i in product_ids)
125
+ url = _api_url(
126
+ f"3/catalog/store/{STORE_ID}/{CATALOG_ID}/productsArray"
127
+ f"?languageId=-1&appId=1&productIds={ids_param}"
128
+ )
129
+ resp = api.get(
130
+ url,
131
+ headers={"Accept": "application/json", "Referer": DRESSES_LANDING},
132
+ )
133
+ if resp.status != 200:
134
+ return []
135
+ try:
136
+ data = json.loads(resp.body())
137
+ except Exception:
138
+ return []
139
+ return data.get("products") or []
140
+
141
+
142
+ def _extract_image_urls(product: dict[str, Any]) -> list[str]:
143
+ """Pull all hero/aux image URLs from the bundleProductSummaries[*].detail.xmedia tree."""
144
+ urls: list[str] = []
145
+ for bps in product.get("bundleProductSummaries") or []:
146
+ det = bps.get("detail") or {}
147
+ for xset in det.get("xmedia") or []:
148
+ for item in xset.get("xmediaItems") or []:
149
+ for media in item.get("medias") or []:
150
+ u = media.get("url")
151
+ if u and u not in urls:
152
+ urls.append(u)
153
+ return urls
154
+
155
+
156
+ def _extract_price_nok(product: dict[str, Any]) -> tuple[float, float, bool]:
157
+ """Returns (price_nok, original_price_nok, on_sale).
158
+
159
+ Inditex stores prices as integer minor-units (NOK*100 for the Norway store).
160
+ Take the first size of the first color of the first bundle as canonical —
161
+ Massimo Dutti rarely varies price across sizes/colors of the same SKU.
162
+ """
163
+ bps = product.get("bundleProductSummaries") or []
164
+ if not bps:
165
+ return (0.0, 0.0, False)
166
+ det = bps[0].get("detail") or {}
167
+ colors = det.get("colors") or []
168
+ if not colors:
169
+ return (0.0, 0.0, False)
170
+ sizes = colors[0].get("sizes") or []
171
+ if not sizes:
172
+ return (0.0, 0.0, False)
173
+ s = sizes[0]
174
+ raw = s.get("price")
175
+ raw_old = s.get("oldPrice")
176
+ try:
177
+ price = float(raw) / 100.0 if raw is not None else 0.0
178
+ except (TypeError, ValueError):
179
+ price = 0.0
180
+ try:
181
+ old = float(raw_old) / 100.0 if raw_old is not None else 0.0
182
+ except (TypeError, ValueError):
183
+ old = 0.0
184
+ on_sale = old > 0 and price > 0 and old > price
185
+ return (price, old, on_sale)
186
+
187
+
188
+ def _is_in_stock(product: dict[str, Any]) -> bool:
189
+ if not product.get("isBuyable"):
190
+ return False
191
+ bps = product.get("bundleProductSummaries") or []
192
+ for b in bps:
193
+ det = b.get("detail") or {}
194
+ for c in det.get("colors") or []:
195
+ for s in c.get("sizes") or []:
196
+ if s.get("isBuyable") and s.get("visibilityValue", "SHOW") == "SHOW":
197
+ return True
198
+ return False
199
+
200
+
201
+ def _to_standard(product: dict[str, Any], category_slug: str) -> dict[str, Any] | None:
202
+ """Map Inditex schema to the taste-engine product dict shape."""
203
+ pid = product.get("id")
204
+ slug = product.get("productUrl")
205
+ if not pid or not slug:
206
+ return None
207
+ url = f"https://www.massimodutti.com/no/en/{slug}.html?pelement={pid}"
208
+ name = product.get("nameEn") or product.get("name") or ""
209
+ images = _extract_image_urls(product)
210
+ price, old_price, on_sale = _extract_price_nok(product)
211
+ color = ""
212
+ bcolors = product.get("bundleColors") or []
213
+ if bcolors:
214
+ color = (bcolors[0].get("name") or "").title()
215
+ family = product.get("familyNameEN") or product.get("familyName") or ""
216
+ subfamily = product.get("subFamilyNameEN") or product.get("subFamilyName") or ""
217
+ cat_text = (subfamily or family or category_slug).lower()
218
+
219
+ return {
220
+ "url": url,
221
+ "external_id": str(pid),
222
+ "store": BRAND,
223
+ "brand": BRAND,
224
+ "name": name,
225
+ "color": color,
226
+ "category": cat_text,
227
+ "price_nok": price,
228
+ "original_price_nok": old_price,
229
+ "currency": "NOK",
230
+ "on_sale": on_sale,
231
+ "image_url": images[0] if images else "",
232
+ "image_urls": json.dumps(images),
233
+ "in_stock": _is_in_stock(product),
234
+ "sizes": json.dumps([
235
+ s.get("name", "")
236
+ for b in (product.get("bundleProductSummaries") or [])
237
+ for c in ((b.get("detail") or {}).get("colors") or [])
238
+ for s in (c.get("sizes") or [])
239
+ if s.get("isBuyable")
240
+ ]),
241
+ }
242
+
243
+
244
+ class MassimoDuttiScraper(BaseScraper):
245
+ """Headless Chromium + Inditex JSON API."""
246
+
247
+ def scrape(
248
+ self,
249
+ categories: list[str] | None = None,
250
+ max_products: int | None = None,
251
+ ) -> list[dict[str, Any]]:
252
+ slugs = [c.strip().lower() for c in (categories or self.config.categories)]
253
+ slugs = [s for s in slugs if s in _CATEGORY_IDS]
254
+ if not slugs:
255
+ slugs = list(_CATEGORY_IDS)
256
+ max_products = max_products or self.config.max_products
257
+
258
+ chromium_path = _resolve_chromium_path()
259
+ if not chromium_path:
260
+ print(
261
+ " Massimo Dutti: full Chromium not found. Run "
262
+ "`uv run --with playwright python -m playwright install chromium-tip-of-tree`",
263
+ flush=True,
264
+ )
265
+ return []
266
+
267
+ try:
268
+ from playwright.sync_api import sync_playwright
269
+ from playwright_stealth import Stealth
270
+ except ImportError:
271
+ print(
272
+ " Massimo Dutti: missing dep. Install with "
273
+ "`uv add playwright playwright-stealth`",
274
+ flush=True,
275
+ )
276
+ return []
277
+
278
+ seen: set[str] = set()
279
+ all_products: list[dict[str, Any]] = []
280
+
281
+ with Stealth().use_sync(sync_playwright()) as pw:
282
+ browser = pw.chromium.launch(
283
+ executable_path=chromium_path,
284
+ headless=True,
285
+ args=["--disable-blink-features=AutomationControlled"],
286
+ )
287
+ try:
288
+ ctx = browser.new_context(
289
+ user_agent=_USER_AGENT,
290
+ locale="en-US",
291
+ timezone_id="Europe/Oslo",
292
+ viewport={"width": 1280, "height": 800},
293
+ extra_http_headers={
294
+ "Accept-Language": "en-US,en;q=0.9,no;q=0.8",
295
+ },
296
+ )
297
+ page = ctx.new_page()
298
+ # Warm cookies — homepage then a category landing.
299
+ page.goto(HOME, wait_until="domcontentloaded", timeout=30000)
300
+ page.wait_for_timeout(4000)
301
+ page.goto(DRESSES_LANDING, wait_until="domcontentloaded", timeout=30000)
302
+ page.wait_for_timeout(5000)
303
+
304
+ cookie_names = {c["name"] for c in ctx.cookies()}
305
+ if "_abck" not in cookie_names:
306
+ print(" Massimo Dutti: Akamai cookie not set, aborting", flush=True)
307
+ return []
308
+
309
+ for slug in slugs:
310
+ if len(all_products) >= max_products:
311
+ break
312
+ cat_id = _CATEGORY_IDS[slug]
313
+ pids = _list_category(ctx.request, cat_id)
314
+ print(f" Massimo Dutti: {slug:<10} cat={cat_id} -> {len(pids)} ids", flush=True)
315
+ if not pids:
316
+ continue
317
+
318
+ for i in range(0, len(pids), _BATCH):
319
+ if len(all_products) >= max_products:
320
+ break
321
+ batch = pids[i : i + _BATCH]
322
+ prods = _fetch_products_batch(ctx.request, batch)
323
+ for p in prods:
324
+ std = _to_standard(p, slug)
325
+ if not std or std["url"] in seen:
326
+ continue
327
+ seen.add(std["url"])
328
+ all_products.append(std)
329
+ if len(all_products) >= max_products:
330
+ break
331
+ finally:
332
+ browser.close()
333
+
334
+ return all_products