File size: 3,560 Bytes
936253d | 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 | 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() |