from __future__ import annotations import json import os import re import time import urllib.parse from typing import Any, Dict, List, Optional, Tuple import requests from smolagents.tools import Tool SCRAPE_DO_SIGNUP_URL = ( "https://dashboard.scrape.do/sign-up?utm_source=huggingface&utm_medium=myntra-scraper" ) API_URL = "https://api.scrape.do/" MYNTRA = "https://www.myntra.com" # Myntra sits behind Akamai Bot Manager; through Scrape.do a plain request (no extra # parameters) returns the full page for 1 credit. CREDITS_PER_REQUEST = 1 PAGE_SIZE = 50 MAX_PAGES = 10 DEFAULT_LISTING_URL = "https://www.myntra.com/men-tshirts?sort=new" DEFAULT_PRODUCT_URL = ( "https://www.myntra.com/lounge-tshirts/levis/levis-men-soft-pure-cotton-round-neck-half-sleeve-tshirt/12027436/buy" ) SEARCH_HEADERS = {"Accept": "application/json", "x-meta-app": "channel=web", "app": "web", "X-myntraweb": "Yes"} _MYX_RE = re.compile(r"window\.__myx\s*=\s*") _decoder = json.JSONDecoder() # ------------------------------------------------------------------ parsing def extract_myx(html: str) -> Dict[str, Any]: """The window.__myx object Myntra renders into every page, or {}.""" match = _MYX_RE.search(html or "") if not match: return {} try: data, _ = _decoder.raw_decode(html, match.end()) except json.JSONDecodeError: return {} return data if isinstance(data, dict) else {} def _pct(price: Any, mrp: Any) -> int: if isinstance(price, (int, float)) and isinstance(mrp, (int, float)) and mrp > 0 and price <= mrp: return round((mrp - price) / mrp * 100) return 0 def _round(value: Any) -> Optional[float]: return round(value, 2) if isinstance(value, (int, float)) and not isinstance(value, bool) else None def _https(url: Any) -> Optional[str]: return url.replace("http://", "https://", 1) if isinstance(url, str) else url def product_url(path_or_id: Any) -> str: text = str(path_or_id or "").strip() if not text: return "" return text if text.startswith("http") else f"{MYNTRA}/{text.lstrip('/')}" def classify_url(text: Optional[str]) -> Optional[str]: """'listing', 'product' or None.""" raw = (text or "").strip() if not raw: return None if not raw.lower().startswith(("http://", "https://")): raw = "https://" + raw parsed = urllib.parse.urlparse(raw) if not parsed.netloc.lower().endswith("myntra.com"): return None path = parsed.path.rstrip("/") if not path: return None if re.search(r"/\d+/buy$", path, re.I) or re.fullmatch(r"/\d+", path): return "product" return "listing" def clean_url(text: str) -> str: raw = text.strip() return raw if raw.lower().startswith(("http://", "https://")) else "https://" + raw def parse_products(items: List[Any]) -> List[Dict[str, Any]]: """Organic products only: sponsored cards carry isPLA and are skipped.""" rows = [] for item in items or []: if not isinstance(item, dict) or item.get("isPLA"): continue price, mrp = item.get("price"), item.get("mrp") article = item.get("articleType") rows.append( { "product_id": item.get("productId"), "name": item.get("productName"), "brand": item.get("brand"), "price_inr": price, "mrp_inr": mrp, "discount_pct": _pct(price, mrp), "rating": _round(item.get("rating")), "rating_count": item.get("ratingCount"), "sizes": item.get("sizes"), "gender": item.get("gender"), "article_type": article.get("typeName") if isinstance(article, dict) else article, "colour": item.get("primaryColour"), "image": _https(item.get("searchImage")), "url": product_url(item.get("landingPageUrl")), } ) return rows def parse_product(html: str) -> Optional[Dict[str, Any]]: """Product summary plus one row per size and seller with that seller's price and units.""" pdp = extract_myx(html).get("pdpData") if not isinstance(pdp, dict) or not pdp.get("id"): return None sellers = {s.get("sellerPartnerId"): s.get("sellerName") for s in pdp.get("sellers") or [] if isinstance(s, dict)} sizes = [] for size in pdp.get("sizes") or []: for offer in size.get("sizeSellerData") or [{}]: sizes.append( { "size": size.get("label"), "available": bool(size.get("available")), "seller": sellers.get(offer.get("sellerPartnerId")), "price_inr": offer.get("discountedPrice"), "mrp_inr": offer.get("mrp"), "units": offer.get("availableCount", 0) if size.get("available") else 0, } ) in_stock = [s for s in sizes if s["available"] and s["units"]] prices = [s["price_inr"] for s in in_stock if isinstance(s["price_inr"], (int, float))] price_block = pdp.get("price") or {} price, mrp = price_block.get("discounted"), price_block.get("mrp", pdp.get("mrp")) ratings = pdp.get("ratings") or {} analytics = pdp.get("analytics") or {} brand = pdp.get("brand") images = [] for album in (pdp.get("media") or {}).get("albums") or []: for img in album.get("images") or []: src = img.get("imageURL") or img.get("secureSrc") or img.get("src") if isinstance(src, str) and src.startswith("http"): images.append(_https(src).replace("($height)", "720").replace("($width)", "540").replace("($qualityPercentage)", "90")) return { "product_id": pdp.get("id"), "name": pdp.get("name"), "brand": brand.get("name") if isinstance(brand, dict) else brand, "price_inr": price, "mrp_inr": mrp, "discount_pct": _pct(price, mrp), "rating": _round(ratings.get("averageRating")), "rating_count": ratings.get("totalCount"), "colour": pdp.get("baseColour"), "article_type": analytics.get("articleType"), "gender": analytics.get("gender"), "country_of_origin": pdp.get("countryOfOrigin"), "sizes_in_stock": len({s["size"] for s in in_stock}), "sizes_total": len(pdp.get("sizes") or []), "units_in_stock": sum(s["units"] for s in in_stock), "lowest_size_price_inr": min(prices) if prices else None, "highest_size_price_inr": max(prices) if prices else None, "sellers": " | ".join(sorted({s["seller"] for s in sizes if s["seller"]})), "attributes": pdp.get("articleAttributes") or {}, "images": images[:6], "url": product_url(pdp.get("landingPageUrl")) or product_url(pdp.get("id")), "sizes": sizes, } def search_api_url(listing_url: str, page: int) -> str: parsed = urllib.parse.urlparse(listing_url) slug = parsed.path.strip("/") query = [(k, v) for k, v in urllib.parse.parse_qsl(parsed.query) if k not in ("p", "o", "rows", "plaEnabled")] query += [("rows", str(PAGE_SIZE)), ("o", str(max(0, (page - 1) * PAGE_SIZE - 1))), ("plaEnabled", "false"), ("p", str(page))] return f"{MYNTRA}/gateway/v4/search/{slug}?{urllib.parse.urlencode(query)}" # --------------------------------------------------------------------- tool class ScrapeDoMyntraTool(Tool): name = "myntra_scraper" description = """ Scrape Myntra (myntra.com), India's largest fashion marketplace. Two modes: - 'listing': products of a listing or search URL (e.g. https://www.myntra.com/men-tshirts?sort=new), 50 per page, with name, brand, price and MRP in rupees, discount, rating, rating count, sizes, colour, image and URL. Sponsored products are left out. Pages beyond the first come from Myntra's search API with a pagination cursor, because the page itself ignores ?p=2. - 'product': one product page (…//buy or myntra.com/): price, MRP, rating, attributes, units in stock, and one row per size and seller with that seller's price and stock. Powered by Scrape.do, which gets past the Akamai Bot Manager Myntra shows to scripts. One credit per request. """ output_type = "string" def __init__(self, api_token: Optional[str] = None) -> None: self._api_token = api_token self.inputs = { "mode": {"type": "string", "description": "'listing' for a listing or search page, 'product' for one product."}, "url": {"type": "string", "description": "A Myntra listing/search URL or product URL."}, "max_pages": { "type": "integer", "description": "For 'listing': pages of 50 products to read. Default 1, maximum 10.", "nullable": True, }, } super().__init__() # ------------------------------------------------------------ plumbing def _resolve_token(self) -> Optional[str]: if self._api_token: return self._api_token.strip() env_token = os.getenv("SCRAPE_DO_API_TOKEN") return env_token.strip() if env_token else None @staticmethod def _missing_token() -> Dict[str, Any]: return {"status": "error", "errorMessage": "Missing Scrape.do API token.", "hint": f"Get a free token at {SCRAPE_DO_SIGNUP_URL}"} def _request(self, token: str, url: str, headers: Optional[Dict[str, str]] = None, want_json: bool = False) -> Dict[str, Any]: """One Scrape.do call with two attempts. Returns {'text', 'headers', 'credits'} or {'_error', ...}.""" params = {"token": token, "url": url} send = None if headers: params["extraHeaders"] = "true" send = {f"sd-{k}": v for k, v in headers.items()} last: Dict[str, Any] = {"_error": "Request failed."} credits = 0 for attempt in (1, 2): started = time.time() print(f"[fetch] attempt {attempt}: {url[:120]}", flush=True) try: response = requests.get(API_URL, params=params, headers=send, timeout=(10, 90)) except requests.exceptions.Timeout: last = {"_error": "Scrape.do didn't answer within 90 seconds. Try again in a minute."} continue except requests.exceptions.RequestException as exc: last = {"_error": f"Request failed: {str(exc).replace(token, '***')[:200]}"} continue body = response.text or "" from_target = "scrape.do-initial-status-code" in {k.lower() for k in response.headers} credits += int(response.headers.get("scrape.do-request-cost") or 0) if response.status_code != 401 or from_target else 0 print(f"[fetch] HTTP {response.status_code}, {len(body)} chars, {time.time() - started:.1f}s", flush=True) if response.status_code == 401 and not from_target: return {"_error": "Scrape.do rejected the token (HTTP 401).", "_auth": True} if response.status_code == 200 and body: ok = True if want_json: try: ok = isinstance(json.loads(body), dict) except ValueError: ok = False else: ok = bool(extract_myx(body)) if ok: return {"text": body, "headers": response.headers, "credits": credits} last = {"_error": "Myntra returned a page without its data (Akamai). Try again."} continue last = {"_error": f"Myntra didn't return the page (HTTP {response.status_code}).", "_status": response.status_code, "_target": from_target} if response.status_code not in (429, 500, 502, 503, 504): break last["credits"] = credits return last @staticmethod def _as_error(data: Dict[str, Any]) -> Dict[str, Any]: result = {"status": "error", "errorMessage": data.get("_error", "Unknown error")} if data.get("_auth"): result["hint"] = f"Check your token or create one at {SCRAPE_DO_SIGNUP_URL}" return result def _session(self, token: str, url: str) -> Tuple[Dict[str, Any], int]: """Visit the listing until Myntra hands out its 'at' session cookie (some visits don't).""" spent = 0 visit: Dict[str, Any] = {} for _ in range(4): visit = self._request(token, url) spent += visit.get("credits", 0) if "_error" in visit: return visit, spent cookies = visit["headers"].get("scrape.do-cookies", "") if any(part.strip().startswith("at=") for part in cookies.split(";")): break return visit, spent # -------------------------------------------------------------- listing def listing(self, url: str, max_pages: Optional[int] = 1) -> Dict[str, Any]: token = self._resolve_token() if not token: return self._missing_token() if classify_url(url) != "listing": return {"status": "error", "errorMessage": "Paste a Myntra listing or search URL, e.g. https://www.myntra.com/men-tshirts"} start = clean_url(url) pages_wanted = max(1, min(int(max_pages or 1), MAX_PAGES)) visit, credits = self._session(token, start) if "_error" in visit: return self._as_error(visit) results = (extract_myx(visit["text"]).get("searchData") or {}).get("results") or {} total = results.get("totalCount") if pages_wanted == 1: rows = parse_products(results.get("products") or []) return {"status": "success", "url": start, "total_count": total, "pages_read": 1, "products": rows, "credits_used": credits} cookies = visit["headers"].get("scrape.do-cookies", "") products: Dict[Any, Dict[str, Any]] = {} cursor, page, refreshes, pages_read = "", 1, 0, 0 while page <= pages_wanted: headers = dict(SEARCH_HEADERS, Cookie=cookies) if cursor: headers["pagination-context"] = cursor res = self._request(token, search_api_url(start, page), headers=headers, want_json=True) credits += res.get("credits", 0) if "_error" in res: if res.get("_target") and res.get("_status") == 401 and refreshes < 2: refreshes += 1 visit, spent = self._session(token, start) credits += spent if "_error" in visit: return self._as_error(visit) cookies = visit["headers"].get("scrape.do-cookies", "") continue if not products: return self._as_error(res) break body = json.loads(res["text"]) rows = parse_products(body.get("products") or []) for row in rows: products.setdefault(row["product_id"], row) pages_read += 1 cursor = res["headers"].get("pagination-context", "") page += 1 if not rows or not body.get("hasNextPage") or not cursor: break return {"status": "success", "url": start, "total_count": total, "pages_read": pages_read, "products": list(products.values()), "credits_used": credits} # -------------------------------------------------------------- product def product(self, url: str) -> Dict[str, Any]: token = self._resolve_token() if not token: return self._missing_token() if classify_url(url) != "product": return {"status": "error", "errorMessage": "Paste a Myntra product URL (…//buy or myntra.com/)."} data = self._request(token, clean_url(url).split("?")[0]) if "_error" in data: return self._as_error(data) product = parse_product(data["text"]) if not product: return {"status": "error", "errorMessage": "That page had no product data. Check the link."} return {"status": "success", "product": product, "credits_used": data.get("credits", CREDITS_PER_REQUEST)} # -------------------------------------------------------------- forward def forward(self, mode: str, url: str, max_pages: Optional[int] = None) -> str: key = (mode or "").strip().lower() if key in ("listing", "search", "category", "listings"): result = self.listing(url, max_pages or 1) elif key in ("product", "details", "item"): result = self.product(url) else: result = {"status": "error", "errorMessage": "mode must be 'listing' or 'product'."} return json.dumps(result, ensure_ascii=False, indent=2)