bugrahans commited on
Commit
dca809d
·
verified ·
1 Parent(s): 20a111c

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +101 -0
  2. app.py +484 -0
  3. requirements.txt +4 -0
  4. tool.py +262 -0
README.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Amazon Product Scraper
3
+ short_description: Scrape Amazon products, sellers and search results as JSON
4
+ emoji: 📦
5
+ colorFrom: yellow
6
+ colorTo: blue
7
+ sdk: gradio
8
+ sdk_version: 6.0.2
9
+ app_file: app.py
10
+ pinned: false
11
+ tags:
12
+ - amazon-scraper
13
+ - amazon
14
+ - product-data
15
+ - price-tracking
16
+ - ecommerce
17
+ - web-scraping
18
+ - scraper
19
+ - data-extraction
20
+ - anti-bot
21
+ - proxy
22
+ - smolagents
23
+ - tool
24
+ - scrape.do
25
+ ---
26
+
27
+ # Amazon Product Scraper — Powered by Scrape.do
28
+
29
+ Pull structured JSON out of any Amazon marketplace: product detail pages, every
30
+ seller offer on an ASIN, and keyword or category search results. No HTML parsing.
31
+
32
+ Powered by the [Scrape.do Amazon Scraper API](https://scrape.do/documentation/amazon-scraper-api/):
33
+
34
+ - Bypasses AWS WAF, CAPTCHAs and rate limits automatically
35
+ - 21 Amazon marketplaces with ZIP-code level delivery targeting
36
+ - Parsed JSON — ASIN, brand, price, list price, rating, images, rankings, specs
37
+ - Organic vs. sponsored flags and exact on-page positions in search
38
+ - 1 credit per successful request
39
+
40
+ ## 🔑 Get your free API token
41
+
42
+ 👉 **[Sign up free on Scrape.do](https://dashboard.scrape.do/sign-up?utm_source=huggingface&utm_medium=amazon-scraper)** — 1,000 successful requests per month, no credit card required.
43
+
44
+ Paste your token into the UI and start scraping.
45
+
46
+ ## Three modes
47
+
48
+ | Tab | Input | Output |
49
+ | --- | --- | --- |
50
+ | **Product page** | Product URL or ASIN | Title, brand, price, list price, rating, images, best seller rankings, technical details |
51
+ | **Seller offers** | Product URL or ASIN | Every active offer with price, condition, seller, fulfilment and Buy Box winner |
52
+ | **Search results** | Keyword + page | Ranked products with ASIN, price, rating, Prime, sponsored flag and badge |
53
+
54
+ Every tab returns the raw JSON response and a CSV download.
55
+
56
+ ## Location targeting
57
+
58
+ Amazon shows different prices, stock and delivery depending on where the buyer is.
59
+
60
+ - **ZIP-level marketplaces** (`us`, `gb`, `de`, `fr`, `it`, `es`, `ca`, `jp`, `in`) — enter a postal code in the **Delivery location** field.
61
+ - **Country-level marketplaces** (`tr`, `br`, `au`, `mx`, `nl`, `pl`, `se`, `ae`, `sa`, `sg`, `eg`, `be`) — enter a delivery country name, or leave it blank to use the marketplace default.
62
+
63
+ ZIP format is validated per marketplace, so `SW1A 1AA` works for `gb` but not for `us`.
64
+
65
+ ## Use as a smolagents Tool
66
+
67
+ ```python
68
+ from smolagents import CodeAgent, InferenceClientModel
69
+ from tool import ScrapeDoAmazonTool
70
+
71
+ agent = CodeAgent(
72
+ tools=[ScrapeDoAmazonTool(api_token="YOUR_SCRAPEDO_TOKEN")],
73
+ model=InferenceClientModel(),
74
+ )
75
+ agent.run("Compare the price and Buy Box seller for ASIN B0BLRJ4R8F in the US and the UK")
76
+ ```
77
+
78
+ You can also set `SCRAPE_DO_API_TOKEN` in your environment and instantiate
79
+ `ScrapeDoAmazonTool()` without arguments.
80
+
81
+ ## Inputs
82
+
83
+ - `mode` *(required)* — `product`, `offers` or `search`.
84
+ - `query` *(required)* — Product URL or ASIN for `product` and `offers`; keyword for `search`.
85
+ - `geocode` *(optional)* — Marketplace country code, defaults to `us`.
86
+ - `zipcode` *(optional)* — ZIP code, or a delivery country name on country-level marketplaces.
87
+ - `page` *(optional)* — Search results page number, defaults to `1`.
88
+ - `language` *(optional)* — Uppercase ISO 639-1 code supported by the marketplace, e.g. `EN`, `DE`.
89
+
90
+ ## Scope
91
+
92
+ Only publicly available product data. Anything behind an Amazon login — account
93
+ pages, the full customer review archive — is out of scope. See the
94
+ [Amazon scraping guide](https://scrape.do/blog/amazon-scraping/) for the legal
95
+ and ethical boundaries.
96
+
97
+ ---
98
+
99
+ Learn more at [scrape.do](https://scrape.do/) · [Documentation](https://scrape.do/documentation/)
100
+
101
+ Check out the configuration reference at <https://huggingface.co/docs/hub/spaces-config-reference>.
app.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import csv
4
+ import os
5
+ import tempfile
6
+ from typing import Any, Dict, List, Optional, Tuple
7
+
8
+ import gradio as gr
9
+
10
+ from tool import (
11
+ MARKETPLACES,
12
+ SCRAPE_DO_SIGNUP_URL,
13
+ ScrapeDoAmazonTool,
14
+ ZIP_LEVEL_MARKETS,
15
+ extract_asin,
16
+ )
17
+
18
+ # ZeroGPU hardware refuses to keep a Space alive unless it finds at least one
19
+ # @spaces.GPU function at startup. This app is pure HTTP and never touches a GPU,
20
+ # so the probe below exists only to satisfy that check. It is never called by the UI.
21
+ try:
22
+ import spaces
23
+
24
+ @spaces.GPU(duration=1)
25
+ def _zerogpu_probe() -> str:
26
+ return "ok"
27
+
28
+ except ImportError:
29
+ pass
30
+
31
+
32
+ MARKET_CHOICES = [(label, code) for code, label in MARKETPLACES.items()]
33
+
34
+ NO_TOKEN_MD = (
35
+ "⚠️ **Please paste your Scrape.do API token above.**\n\n"
36
+ f"Don't have one yet? [Get a free token in 30 seconds → ]({SCRAPE_DO_SIGNUP_URL})\n\n"
37
+ "Free tier includes 1,000 successful requests / month, no credit card required."
38
+ )
39
+
40
+
41
+ # --------------------------------------------------------------------- helpers
42
+
43
+
44
+ def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]:
45
+ """Write rows to a temp CSV and return its path."""
46
+ if not rows:
47
+ return None
48
+ fieldnames: List[str] = []
49
+ for row in rows:
50
+ for key in row:
51
+ if key not in fieldnames:
52
+ fieldnames.append(key)
53
+
54
+ handle = tempfile.NamedTemporaryFile(
55
+ mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False,
56
+ newline="", encoding="utf-8-sig",
57
+ )
58
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
59
+ writer.writeheader()
60
+ for row in rows:
61
+ writer.writerow({key: row.get(key, "") for key in fieldnames})
62
+ handle.close()
63
+ return handle.name
64
+
65
+
66
+ def _error_md(data: Dict[str, Any]) -> str:
67
+ message = data.get("errorMessage") or data.get("message") or data.get("error") or "Unknown error"
68
+ hint = data.get("hint")
69
+ text = f"❌ **{message}**"
70
+ if hint:
71
+ text += f"\n\n{hint}"
72
+ return text
73
+
74
+
75
+ def _money(amount: Any, symbol: str = "", code: str = "") -> str:
76
+ if amount in (None, ""):
77
+ return "—"
78
+ if symbol:
79
+ return f"{symbol}{amount}"
80
+ if code:
81
+ return f"{amount} {code}"
82
+ return str(amount)
83
+
84
+
85
+ def _tool_or_none(token: str) -> Optional[ScrapeDoAmazonTool]:
86
+ if not token or not token.strip():
87
+ return None
88
+ return ScrapeDoAmazonTool(api_token=token.strip())
89
+
90
+
91
+ # --------------------------------------------------------------- product (PDP)
92
+
93
+
94
+ def scrape_product(
95
+ token: str, query: str, geocode: str, zipcode: str, language: str
96
+ ) -> Tuple[str, List[str], Dict[str, Any], Optional[str]]:
97
+ tool = _tool_or_none(token)
98
+ if tool is None:
99
+ return NO_TOKEN_MD, [], {}, None
100
+ if not query or not query.strip():
101
+ return "⚠️ **Paste an Amazon product URL or ASIN.**", [], {}, None
102
+
103
+ data = tool.request("product", query, geocode, zipcode, language=language)
104
+ if data.get("status") != "success":
105
+ return _error_md(data), [], data, None
106
+
107
+ symbol = data.get("currency_symbol") or ""
108
+ code = data.get("currency") or ""
109
+ price = _money(data.get("price"), symbol, code)
110
+ list_price = data.get("list_price")
111
+
112
+ lines = [f"## {data.get('name') or 'Untitled product'}", ""]
113
+
114
+ facts = [
115
+ f"**ASIN** `{data.get('asin', '—')}`",
116
+ f"**Brand** {data.get('brand') or '—'}",
117
+ f"**Price** {price}",
118
+ ]
119
+ if list_price:
120
+ facts.append(f"**List price** ~~{_money(list_price, symbol, code)}~~")
121
+ if data.get("rating") is not None:
122
+ facts.append(
123
+ f"**Rating** {data.get('rating')} ★ ({data.get('total_ratings') or 0:,} ratings)"
124
+ )
125
+ facts.append("**Prime** " + ("yes" if data.get("is_prime") else "no"))
126
+ lines.append(" · ".join(facts))
127
+
128
+ shipping = data.get("shipping_info") or []
129
+ if shipping:
130
+ lines += ["", "**Delivery**"] + [f"- {item}" for item in shipping[:4]]
131
+
132
+ rankings = data.get("best_seller_rankings") or []
133
+ if rankings:
134
+ lines += ["", "**Best seller rankings**"]
135
+ for rank in rankings[:6]:
136
+ lines.append(f"- #{rank.get('rank')} in {rank.get('category')}")
137
+
138
+ details = data.get("technical_details") or {}
139
+ if isinstance(details, dict) and details:
140
+ lines += ["", "**Technical details**", "", "| Field | Value |", "| --- | --- |"]
141
+ for key, value in list(details.items())[:15]:
142
+ lines.append(f"| {key} | {value} |")
143
+
144
+ description = data.get("description")
145
+ if description:
146
+ lines += ["", "**Description**", "", str(description)[:1200]]
147
+
148
+ if data.get("url"):
149
+ lines += ["", f"[Open on Amazon →]({data['url']})"]
150
+
151
+ images = [
152
+ image.get("url")
153
+ for image in (data.get("images") or [])
154
+ if isinstance(image, dict) and image.get("url")
155
+ ]
156
+ if not images and data.get("thumbnail"):
157
+ images = [data["thumbnail"]]
158
+
159
+ flat = {
160
+ "asin": data.get("asin"),
161
+ "name": data.get("name"),
162
+ "brand": data.get("brand"),
163
+ "price": data.get("price"),
164
+ "list_price": data.get("list_price"),
165
+ "currency": data.get("currency"),
166
+ "rating": data.get("rating"),
167
+ "total_ratings": data.get("total_ratings"),
168
+ "is_prime": data.get("is_prime"),
169
+ "url": data.get("url"),
170
+ "thumbnail": data.get("thumbnail"),
171
+ }
172
+ csv_path = _write_csv([flat], f"amazon-product-{data.get('asin', 'result')}")
173
+
174
+ return "\n".join(lines), images[:12], data, csv_path
175
+
176
+
177
+ # ------------------------------------------------------------------- offers
178
+
179
+
180
+ OFFER_HEADERS = [
181
+ "Condition", "Seller", "Price", "Currency",
182
+ "Ships from", "FBA", "Prime", "Buy Box",
183
+ ]
184
+
185
+
186
+ def scrape_offers(
187
+ token: str, query: str, geocode: str, zipcode: str, language: str
188
+ ) -> Tuple[str, List[List[Any]], Dict[str, Any], Optional[str]]:
189
+ tool = _tool_or_none(token)
190
+ if tool is None:
191
+ return NO_TOKEN_MD, [], {}, None
192
+ if not query or not query.strip():
193
+ return "⚠️ **Paste an Amazon product URL or ASIN.**", [], {}, None
194
+
195
+ data = tool.request("offers", query, geocode, zipcode, language=language)
196
+ if data.get("status") != "success":
197
+ return _error_md(data), [], data, None
198
+
199
+ offers = data.get("offers") or []
200
+ if not offers:
201
+ return (
202
+ f"No competing offers returned for `{data.get('asin')}` in this "
203
+ "marketplace and delivery location. That is a valid result, not an "
204
+ "error — try another ZIP code or marketplace.",
205
+ [], data, None,
206
+ )
207
+
208
+ rows: List[List[Any]] = []
209
+ flat_rows: List[Dict[str, Any]] = []
210
+ for offer in offers:
211
+ listing = offer.get("listingPrice") or {}
212
+ prime = (offer.get("primeInformation") or {}).get("isPrime")
213
+ row = {
214
+ "asin": data.get("asin"),
215
+ "condition": offer.get("condition") or "",
216
+ "seller": offer.get("merchantName") or "",
217
+ "price": listing.get("amount", ""),
218
+ "currency": listing.get("currency", ""),
219
+ "ships_from": offer.get("shipsFrom") or "",
220
+ "fulfilled_by_amazon": bool(offer.get("isFulfilledByAmazon")),
221
+ "is_prime": bool(prime),
222
+ "is_buy_box_winner": bool(offer.get("isBuyBoxWinner")),
223
+ }
224
+ flat_rows.append(row)
225
+ rows.append([
226
+ row["condition"], row["seller"], row["price"], row["currency"],
227
+ row["ships_from"],
228
+ "✓" if row["fulfilled_by_amazon"] else "",
229
+ "✓" if row["is_prime"] else "",
230
+ "✓" if row["is_buy_box_winner"] else "",
231
+ ])
232
+
233
+ prices = [
234
+ offer["price"] for offer in flat_rows
235
+ if isinstance(offer["price"], (int, float))
236
+ ]
237
+ summary = f"**{len(rows)} offer(s)** for ASIN `{data.get('asin')}`"
238
+ if prices:
239
+ summary += f" · lowest {min(prices)} · highest {max(prices)}"
240
+ buy_box = next((o["seller"] for o in flat_rows if o["is_buy_box_winner"]), None)
241
+ if buy_box:
242
+ summary += f" · Buy Box: **{buy_box}**"
243
+
244
+ csv_path = _write_csv(flat_rows, f"amazon-offers-{data.get('asin', 'result')}")
245
+ return summary, rows, data, csv_path
246
+
247
+
248
+ # ------------------------------------------------------------------- search
249
+
250
+
251
+ SEARCH_HEADERS = [
252
+ "#", "ASIN", "Title", "Price", "Rating", "Reviews", "Prime", "Sponsored", "Badge",
253
+ ]
254
+
255
+
256
+ def scrape_search(
257
+ token: str, keyword: str, geocode: str, zipcode: str, page: int, language: str
258
+ ) -> Tuple[str, List[List[Any]], Dict[str, Any], Optional[str]]:
259
+ tool = _tool_or_none(token)
260
+ if tool is None:
261
+ return NO_TOKEN_MD, [], {}, None
262
+ if not keyword or not keyword.strip():
263
+ return "⚠️ **Enter a search keyword.**", [], {}, None
264
+
265
+ data = tool.request("search", keyword, geocode, zipcode, page=page, language=language)
266
+ if data.get("status") != "success":
267
+ return _error_md(data), [], data, None
268
+
269
+ products = data.get("products") or []
270
+ if not products:
271
+ return "No products returned for that keyword.", [], data, None
272
+
273
+ rows: List[List[Any]] = []
274
+ flat_rows: List[Dict[str, Any]] = []
275
+ for product in products:
276
+ price = product.get("price") or {}
277
+ rating = product.get("rating") or {}
278
+ row = {
279
+ "position": product.get("position"),
280
+ "asin": product.get("asin"),
281
+ "title": product.get("title"),
282
+ "price": price.get("amount", ""),
283
+ "currency": price.get("currencyCode", ""),
284
+ "rating": rating.get("value", ""),
285
+ "rating_count": rating.get("count", ""),
286
+ "review_count": product.get("reviewCount", ""),
287
+ "is_prime": bool(product.get("isPrime")),
288
+ "is_sponsored": bool(product.get("isSponsored")),
289
+ "badge": product.get("badge") or "",
290
+ "url": product.get("url"),
291
+ "image_url": product.get("imageUrl"),
292
+ }
293
+ flat_rows.append(row)
294
+ title = row["title"] or ""
295
+ rows.append([
296
+ row["position"], row["asin"],
297
+ title[:90] + ("…" if len(title) > 90 else ""),
298
+ f"{row['price']} {row['currency']}".strip(),
299
+ row["rating"], row["review_count"],
300
+ "✓" if row["is_prime"] else "",
301
+ "✓" if row["is_sponsored"] else "",
302
+ row["badge"],
303
+ ])
304
+
305
+ sponsored = sum(1 for product in flat_rows if product["is_sponsored"])
306
+ summary = (
307
+ f"**{len(rows)} results** for “{data.get('keyword')}” · page {data.get('page')} · "
308
+ f"{sponsored} sponsored, {len(rows) - sponsored} organic"
309
+ )
310
+ if data.get("totalResults"):
311
+ summary += f" · {data['totalResults']}"
312
+
313
+ csv_path = _write_csv(flat_rows, "amazon-search")
314
+ return summary, rows, data, csv_path
315
+
316
+
317
+ # ----------------------------------------------------------------------- UI
318
+
319
+
320
+ HEADER_MD = f"""
321
+ # 📦 Amazon Product Scraper
322
+
323
+ **Pull structured JSON from any Amazon marketplace — product pages, every seller
324
+ offer, and keyword search results.** No HTML parsing, no ASIN spreadsheets, no blocks.
325
+
326
+ AWS WAF bypass, proxy rotation, session handling and CAPTCHAs are handled for you
327
+ across 21 marketplaces, with ZIP-code level delivery targeting.
328
+ Powered by [Scrape.do](https://scrape.do/).
329
+
330
+ ### 🔑 Need an API token?
331
+ 👉 **[Sign up free on Scrape.do]({SCRAPE_DO_SIGNUP_URL})** — 1,000 free requests / month, no credit card.
332
+ """
333
+
334
+ FOOTER_MD = f"""
335
+ ---
336
+
337
+ ### Using this as a smolagents Tool
338
+
339
+ ```python
340
+ from smolagents import CodeAgent, InferenceClientModel
341
+ from tool import ScrapeDoAmazonTool
342
+
343
+ agent = CodeAgent(
344
+ tools=[ScrapeDoAmazonTool(api_token="YOUR_SCRAPEDO_TOKEN")],
345
+ model=InferenceClientModel(),
346
+ )
347
+ agent.run("Compare the price and Buy Box seller for ASIN B0BLRJ4R8F in the US and the UK")
348
+ ```
349
+
350
+ Or set `SCRAPE_DO_API_TOKEN` in your environment and instantiate without args.
351
+
352
+ Only publicly available product data is in scope. Anything behind an Amazon login —
353
+ account pages, full customer review archives — is out of bounds; see the
354
+ [Amazon scraping guide](https://scrape.do/blog/amazon-scraping/) for the legal and
355
+ ethical boundaries.
356
+
357
+ [Scrape.do](https://scrape.do/) · [Amazon Scraper API docs](https://scrape.do/documentation/amazon-scraper-api/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL})
358
+ """
359
+
360
+ ZIP_INFO = (
361
+ "ZIP code for us / gb / de / fr / it / es / ca / jp / in. "
362
+ "For other marketplaces, enter a delivery country name instead (or leave blank)."
363
+ )
364
+
365
+
366
+ def build_demo() -> gr.Blocks:
367
+ with gr.Blocks(title="Amazon Product Scraper — Scrape.do") as demo:
368
+ gr.Markdown(HEADER_MD)
369
+
370
+ api_token = gr.Textbox(
371
+ label="Scrape.do API Token",
372
+ placeholder="Paste your token here…",
373
+ type="password",
374
+ info="Don't have one? Get a free token from the link above.",
375
+ )
376
+
377
+ with gr.Row():
378
+ geocode = gr.Dropdown(
379
+ label="Marketplace",
380
+ choices=MARKET_CHOICES,
381
+ value="us",
382
+ )
383
+ zipcode = gr.Textbox(
384
+ label="Delivery location",
385
+ placeholder="10001",
386
+ info=ZIP_INFO,
387
+ )
388
+ language = gr.Textbox(
389
+ label="Language",
390
+ placeholder="EN",
391
+ info="Optional ISO 639-1 code, uppercase. Must be supported by the marketplace.",
392
+ )
393
+
394
+ with gr.Tabs():
395
+ # ------------------------------------------------ product tab
396
+ with gr.Tab("Product page"):
397
+ gr.Markdown(
398
+ "Paste a product URL or a bare ASIN. Returns title, brand, price, "
399
+ "list price, rating, images, best seller rankings and specs."
400
+ )
401
+ product_query = gr.Textbox(
402
+ label="Amazon product URL or ASIN",
403
+ placeholder="https://www.amazon.com/dp/B0BLRJ4R8F · or just B0BLRJ4R8F",
404
+ )
405
+ product_btn = gr.Button("Scrape product", variant="primary")
406
+
407
+ product_summary = gr.Markdown()
408
+ product_gallery = gr.Gallery(
409
+ label="Product images", columns=6, height=180, preview=False
410
+ )
411
+ product_csv = gr.File(label="Download CSV")
412
+ with gr.Accordion("Raw JSON response", open=False):
413
+ product_json = gr.JSON()
414
+
415
+ product_btn.click(
416
+ fn=scrape_product,
417
+ inputs=[api_token, product_query, geocode, zipcode, language],
418
+ outputs=[product_summary, product_gallery, product_json, product_csv],
419
+ )
420
+
421
+ # ------------------------------------------------- offers tab
422
+ with gr.Tab("Seller offers"):
423
+ gr.Markdown(
424
+ "Every active offer on an ASIN: price, condition, seller, "
425
+ "fulfilment and who currently holds the Buy Box."
426
+ )
427
+ offers_query = gr.Textbox(
428
+ label="Amazon product URL or ASIN",
429
+ placeholder="B0DZDBWM5B",
430
+ )
431
+ offers_btn = gr.Button("Scrape offers", variant="primary")
432
+
433
+ offers_summary = gr.Markdown()
434
+ offers_table = gr.Dataframe(
435
+ headers=OFFER_HEADERS, wrap=True, label="Offers"
436
+ )
437
+ offers_csv = gr.File(label="Download CSV")
438
+ with gr.Accordion("Raw JSON response", open=False):
439
+ offers_json = gr.JSON()
440
+
441
+ offers_btn.click(
442
+ fn=scrape_offers,
443
+ inputs=[api_token, offers_query, geocode, zipcode, language],
444
+ outputs=[offers_summary, offers_table, offers_json, offers_csv],
445
+ )
446
+
447
+ # ------------------------------------------------- search tab
448
+ with gr.Tab("Search results"):
449
+ gr.Markdown(
450
+ "Keyword and category search with organic vs. sponsored "
451
+ "placements and exact on-page positions."
452
+ )
453
+ with gr.Row():
454
+ search_query = gr.Textbox(
455
+ label="Search keyword",
456
+ placeholder="laptop stands",
457
+ scale=3,
458
+ )
459
+ search_page = gr.Number(
460
+ label="Page", value=1, precision=0, minimum=1, scale=1
461
+ )
462
+ search_btn = gr.Button("Scrape search results", variant="primary")
463
+
464
+ search_summary = gr.Markdown()
465
+ search_table = gr.Dataframe(
466
+ headers=SEARCH_HEADERS, wrap=True, label="Results"
467
+ )
468
+ search_csv = gr.File(label="Download CSV")
469
+ with gr.Accordion("Raw JSON response", open=False):
470
+ search_json = gr.JSON()
471
+
472
+ search_btn.click(
473
+ fn=scrape_search,
474
+ inputs=[api_token, search_query, geocode, zipcode, search_page, language],
475
+ outputs=[search_summary, search_table, search_json, search_csv],
476
+ )
477
+
478
+ gr.Markdown(FOOTER_MD)
479
+
480
+ return demo
481
+
482
+
483
+ if __name__ == "__main__":
484
+ build_demo().launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ gradio
2
+ requests
3
+ smolagents
4
+ spaces
tool.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import re
6
+ import urllib.parse
7
+ from typing import Any, Dict, Optional
8
+
9
+ import requests
10
+ from smolagents.tools import Tool
11
+
12
+
13
+ SCRAPE_DO_SIGNUP_URL = (
14
+ "https://dashboard.scrape.do/sign-up?utm_source=huggingface&utm_medium=amazon-scraper"
15
+ )
16
+ API_BASE = "https://api.scrape.do/plugin/amazon"
17
+
18
+ # geocode -> human label, shown in the UI dropdown.
19
+ MARKETPLACES: Dict[str, str] = {
20
+ "us": "United States (amazon.com)",
21
+ "gb": "United Kingdom (amazon.co.uk)",
22
+ "de": "Germany (amazon.de)",
23
+ "fr": "France (amazon.fr)",
24
+ "it": "Italy (amazon.it)",
25
+ "es": "Spain (amazon.es)",
26
+ "ca": "Canada (amazon.ca)",
27
+ "jp": "Japan (amazon.co.jp)",
28
+ "in": "India (amazon.in)",
29
+ "au": "Australia (amazon.com.au)",
30
+ "br": "Brazil (amazon.com.br)",
31
+ "mx": "Mexico (amazon.com.mx)",
32
+ "nl": "Netherlands (amazon.nl)",
33
+ "pl": "Poland (amazon.pl)",
34
+ "se": "Sweden (amazon.se)",
35
+ "tr": "Turkey (amazon.com.tr)",
36
+ "ae": "UAE (amazon.ae)",
37
+ "sa": "Saudi Arabia (amazon.sa)",
38
+ "sg": "Singapore (amazon.sg)",
39
+ "eg": "Egypt (amazon.eg)",
40
+ "be": "Belgium (amazon.com.be)",
41
+ }
42
+
43
+ # Marketplaces where Amazon localises delivery by postal code. Everything else
44
+ # takes a country-level location instead, via countryName.
45
+ ZIP_LEVEL_MARKETS = {"us", "gb", "uk", "de", "fr", "it", "es", "ca", "jp", "in"}
46
+
47
+ COUNTRY_NAMES: Dict[str, str] = {
48
+ "tr": "Turkey",
49
+ "br": "Brazil",
50
+ "au": "Australia",
51
+ "mx": "Mexico",
52
+ "nl": "Netherlands",
53
+ "pl": "Poland",
54
+ "se": "Sweden",
55
+ "ae": "United Arab Emirates",
56
+ "sa": "Saudi Arabia",
57
+ "sg": "Singapore",
58
+ "eg": "Egypt",
59
+ "be": "Belgium",
60
+ }
61
+
62
+ _ASIN_PATTERN = re.compile(r"(?:/dp/|/gp/product/|/gp/aw/d/|/product/|[?&]asin=)([A-Z0-9]{10})", re.I)
63
+ _BARE_ASIN = re.compile(r"^[A-Z0-9]{10}$", re.I)
64
+
65
+
66
+ def extract_asin(value: str) -> Optional[str]:
67
+ """Accept a full Amazon URL or a bare ASIN and return the ASIN."""
68
+ if not value:
69
+ return None
70
+ value = value.strip()
71
+
72
+ if _BARE_ASIN.match(value):
73
+ return value.upper()
74
+
75
+ match = _ASIN_PATTERN.search(value)
76
+ if match:
77
+ return match.group(1).upper()
78
+
79
+ return None
80
+
81
+
82
+ class ScrapeDoAmazonTool(Tool):
83
+ name = "amazon_product_scraper"
84
+ description = """
85
+ Scrape structured product data from any Amazon marketplace: product detail
86
+ pages (title, brand, price, rating, images, rankings, technical specs),
87
+ all seller offers for an ASIN, or keyword search results with organic and
88
+ sponsored positions. Returns clean JSON, no HTML parsing required.
89
+ Powered by Scrape.do's Amazon Scraper API, which handles AWS WAF, proxy
90
+ rotation, sessions and CAPTCHAs automatically across 21 marketplaces.
91
+ Use this when you need Amazon pricing, catalogue or competitive data.
92
+ """
93
+ output_type = "string"
94
+
95
+ def __init__(self, api_token: Optional[str] = None) -> None:
96
+ # Token can be passed explicitly (e.g. by a Gradio UI) or read from the
97
+ # SCRAPE_DO_API_TOKEN environment variable for programmatic use.
98
+ self._api_token = api_token
99
+ self.inputs = {
100
+ "mode": {
101
+ "type": "string",
102
+ "description": (
103
+ "What to scrape: 'product' for a product detail page, "
104
+ "'offers' for every seller offer on an ASIN, or 'search' "
105
+ "for keyword/category search results."
106
+ ),
107
+ },
108
+ "query": {
109
+ "type": "string",
110
+ "description": (
111
+ "An Amazon product URL or ASIN for 'product' and 'offers'. "
112
+ "A search keyword for 'search'."
113
+ ),
114
+ },
115
+ "geocode": {
116
+ "type": "string",
117
+ "description": (
118
+ "Marketplace country code: 'us', 'gb', 'de', 'jp', 'tr'… "
119
+ "Defaults to 'us'."
120
+ ),
121
+ "nullable": True,
122
+ },
123
+ "zipcode": {
124
+ "type": "string",
125
+ "description": (
126
+ "Postal code for ZIP-level marketplaces (us, gb, de, fr, it, "
127
+ "es, ca, jp, in) to localise price, stock and delivery. "
128
+ "Ignored elsewhere, where a country-level location is used."
129
+ ),
130
+ "nullable": True,
131
+ },
132
+ "page": {
133
+ "type": "integer",
134
+ "description": "Search results page number. Only used when mode='search'.",
135
+ "nullable": True,
136
+ },
137
+ "language": {
138
+ "type": "string",
139
+ "description": (
140
+ "ISO 639-1 language code in uppercase, e.g. 'EN', 'DE', 'FR'. "
141
+ "Must be supported by the target marketplace."
142
+ ),
143
+ "nullable": True,
144
+ },
145
+ }
146
+ super().__init__()
147
+
148
+ # ------------------------------------------------------------------ token
149
+
150
+ def _resolve_token(self) -> Optional[str]:
151
+ if self._api_token:
152
+ return self._api_token.strip()
153
+ env_token = os.getenv("SCRAPE_DO_API_TOKEN")
154
+ return env_token.strip() if env_token else None
155
+
156
+ # ---------------------------------------------------------------- request
157
+
158
+ def request(
159
+ self,
160
+ mode: str,
161
+ query: str,
162
+ geocode: str = "us",
163
+ zipcode: Optional[str] = None,
164
+ page: Optional[int] = None,
165
+ language: Optional[str] = None,
166
+ ) -> Dict[str, Any]:
167
+ """Call the Amazon Scraper API and return a parsed dict."""
168
+ token = self._resolve_token()
169
+ if not token:
170
+ return {
171
+ "status": "error",
172
+ "errorMessage": "Missing Scrape.do API token.",
173
+ "hint": f"Get a free token at {SCRAPE_DO_SIGNUP_URL}",
174
+ }
175
+
176
+ if not query or not query.strip():
177
+ return {"status": "error", "errorMessage": "No ASIN, URL or keyword provided."}
178
+
179
+ geocode = (geocode or "us").strip().lower()
180
+ params: Dict[str, Any] = {"token": token, "geocode": geocode}
181
+
182
+ if mode in ("product", "offers"):
183
+ asin = extract_asin(query)
184
+ if not asin:
185
+ return {
186
+ "status": "error",
187
+ "errorMessage": (
188
+ "Could not read an ASIN from that input. Paste a full "
189
+ "Amazon product URL (…/dp/B0BLRJ4R8F) or the 10-character "
190
+ "ASIN on its own."
191
+ ),
192
+ }
193
+ params["asin"] = asin
194
+ endpoint = f"{API_BASE}/pdp" if mode == "product" else f"{API_BASE}/offer-listing"
195
+ elif mode == "search":
196
+ params["keyword"] = query.strip()
197
+ params["page"] = int(page or 1)
198
+ endpoint = f"{API_BASE}/search"
199
+ else:
200
+ return {"status": "error", "errorMessage": f"Unknown mode: {mode}"}
201
+
202
+ # Location: ZIP for ZIP-level marketplaces, country name for the rest.
203
+ if geocode in ZIP_LEVEL_MARKETS:
204
+ if zipcode and zipcode.strip():
205
+ params["zipcode"] = zipcode.strip()
206
+ elif geocode in COUNTRY_NAMES:
207
+ # Passing the marketplace's own country is a no-op, so only send it
208
+ # when the caller explicitly asked for a different delivery country.
209
+ if zipcode and zipcode.strip():
210
+ params["countryName"] = zipcode.strip()
211
+
212
+ if language and language.strip():
213
+ params["language"] = language.strip().upper()
214
+
215
+ url = endpoint + "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote)
216
+
217
+ try:
218
+ response = requests.get(url, timeout=90)
219
+ except requests.exceptions.RequestException as exc:
220
+ return {"status": "error", "errorMessage": f"Request failed: {exc}"}
221
+
222
+ try:
223
+ data = response.json()
224
+ except ValueError:
225
+ return {
226
+ "status": "error",
227
+ "errorMessage": f"Unexpected non-JSON response (HTTP {response.status_code}).",
228
+ "details": response.text[:500],
229
+ }
230
+
231
+ if response.status_code == 401 or "token" in str(data.get("error", "")).lower():
232
+ data.setdefault(
233
+ "hint", f"Check your token or create one at {SCRAPE_DO_SIGNUP_URL}"
234
+ )
235
+
236
+ if isinstance(data, dict) and "status" not in data:
237
+ data["status"] = "success" if response.ok else "error"
238
+ if isinstance(data, dict) and not response.ok and not data.get("errorMessage"):
239
+ data["errorMessage"] = data.get("message") or f"HTTP {response.status_code}"
240
+
241
+ return data
242
+
243
+ # ---------------------------------------------------------------- forward
244
+
245
+ def forward(
246
+ self,
247
+ mode: str = "product",
248
+ query: str = "",
249
+ geocode: Optional[str] = None,
250
+ zipcode: Optional[str] = None,
251
+ page: Optional[int] = None,
252
+ language: Optional[str] = None,
253
+ ) -> str:
254
+ result = self.request(
255
+ mode=mode,
256
+ query=query,
257
+ geocode=geocode or "us",
258
+ zipcode=zipcode,
259
+ page=page,
260
+ language=language,
261
+ )
262
+ return json.dumps(result, ensure_ascii=False, indent=2)