Parveshiiii's picture
Upload 1585 files
936253d verified
Raw History Blame Contribute Delete
3.56 kB
import argparse
import json
import re
from pathlib import Path
from typing import Any, Dict, List
import urllib.parse
from scraper.flipkart import FlipkartScraper
DEFAULT_RESULT_LIMIT = 1500
# Suffixes added to the brand name for multiple product queries
KEYWORD_SUFFIXES = (
"",
"bag",
"bags",
"handbag",
"belt",
"wallet",
"shoes",
"sneakers",
"sunglasses",
"watch",
"fashion",
"luxury",
"vintage",
"accessories",
)
PROJECT_ROOT = Path(__file__).resolve().parents[1]
def build_search_url(query: str) -> str:
"""Builds Flipkart search URL using query parameters."""
encoded_query = urllib.parse.quote_plus(query.strip())
return (
f"https://www.flipkart.com/search?q={encoded_query}"
"&otracker=search&otracker1=search&marketplace=FLIPKART&as-show=on&as=off"
)
def build_run_input(start_url: str, results_wanted: int) -> Dict[str, Any]:
"""Prepares the Apify actor input payload."""
return {
"startUrl": start_url,
"results_wanted": results_wanted,
}
def save_results(
items: List[Dict[str, Any]],
brand: str,
search_urls: List[str],
output_path: Path,
) -> None:
output_path.parent.mkdir(parents=True, exist_ok=True)
data = {
"brand": brand,
"search_urls": search_urls,
"results_count": len(items),
"products": items,
}
output_path.write_text(
json.dumps(data, ensure_ascii=False, indent=2, default=str),
encoding="utf-8",
)
def main() -> None:
parser = argparse.ArgumentParser(description="Scrape Flipkart products by brand keywords")
parser.add_argument("--brand", default="gucci", help="Brand name; defaults to Gucci")
parser.add_argument(
"--limit",
type=int,
default=DEFAULT_RESULT_LIMIT,
help=f"Total target product limit across all keywords (default: {DEFAULT_RESULT_LIMIT})",
)
parser.add_argument("--output", type=Path, help="JSON output path")
args = parser.parse_args()
brand_clean = args.brand.strip()
if not brand_clean:
raise ValueError("Brand cannot be empty")
per_query_limit = max(10, args.limit // len(KEYWORD_SUFFIXES))
all_products: List[Dict[str, Any]] = []
seen_ids = set()
search_urls: List[str] = []
for suffix in KEYWORD_SUFFIXES:
query = f"{brand_clean} {suffix}".strip()
search_url = build_search_url(query)
search_urls.append(search_url)
print(f"Scraping query: '{query}' -> {search_url}")
run_input = build_run_input(search_url, results_wanted=per_query_limit)
try:
scraper = FlipkartScraper(run_input=run_input)
for item in scraper.run():
# Deduplicate by productId, url, or title
item_id = item.get("productId") or item.get("url") or item.get("title")
if item_id and item_id in seen_ids:
continue
if item_id:
seen_ids.add(item_id)
all_products.append(item)
except Exception as e:
print(f"Error scraping '{query}': {e}")
# Stop early if total limit reached
if len(all_products) >= args.limit:
break
output_path = args.output or PROJECT_ROOT / "data" / f"{brand_clean.lower()}_flipkart.json"
save_results(all_products, brand_clean, search_urls, output_path)
print(f"Saved {len(all_products)} unique products to {output_path}")
if __name__ == "__main__":
main()