bugrahans commited on
Commit
75cee27
·
verified ·
1 Parent(s): dd13c07

Upload 4 files

Browse files
Files changed (4) hide show
  1. README.md +95 -9
  2. app.py +470 -0
  3. requirements.txt +3 -0
  4. tool.py +262 -0
README.md CHANGED
@@ -1,15 +1,101 @@
1
  ---
2
- title: Amazon Scraper Tool
3
- emoji: 🌍
4
- colorFrom: green
5
- colorTo: indigo
 
6
  sdk: gradio
7
- sdk_version: 6.26.0
8
- python_version: '3.12'
9
  app_file: app.py
10
  pinned: false
11
- license: mit
12
- short_description: Scrape Amazon products, sellers and search results as JSON
 
 
 
 
 
 
 
 
 
 
 
 
13
  ---
14
 
15
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,470 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ MARKET_CHOICES = [(label, code) for code, label in MARKETPLACES.items()]
19
+
20
+ NO_TOKEN_MD = (
21
+ "⚠️ **Please paste your Scrape.do API token above.**\n\n"
22
+ f"Don't have one yet? [Get a free token in 30 seconds → ]({SCRAPE_DO_SIGNUP_URL})\n\n"
23
+ "Free tier includes 1,000 successful requests / month, no credit card required."
24
+ )
25
+
26
+
27
+ # --------------------------------------------------------------------- helpers
28
+
29
+
30
+ def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]:
31
+ """Write rows to a temp CSV and return its path."""
32
+ if not rows:
33
+ return None
34
+ fieldnames: List[str] = []
35
+ for row in rows:
36
+ for key in row:
37
+ if key not in fieldnames:
38
+ fieldnames.append(key)
39
+
40
+ handle = tempfile.NamedTemporaryFile(
41
+ mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False,
42
+ newline="", encoding="utf-8-sig",
43
+ )
44
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
45
+ writer.writeheader()
46
+ for row in rows:
47
+ writer.writerow({key: row.get(key, "") for key in fieldnames})
48
+ handle.close()
49
+ return handle.name
50
+
51
+
52
+ def _error_md(data: Dict[str, Any]) -> str:
53
+ message = data.get("errorMessage") or data.get("message") or data.get("error") or "Unknown error"
54
+ hint = data.get("hint")
55
+ text = f"❌ **{message}**"
56
+ if hint:
57
+ text += f"\n\n{hint}"
58
+ return text
59
+
60
+
61
+ def _money(amount: Any, symbol: str = "", code: str = "") -> str:
62
+ if amount in (None, ""):
63
+ return "—"
64
+ if symbol:
65
+ return f"{symbol}{amount}"
66
+ if code:
67
+ return f"{amount} {code}"
68
+ return str(amount)
69
+
70
+
71
+ def _tool_or_none(token: str) -> Optional[ScrapeDoAmazonTool]:
72
+ if not token or not token.strip():
73
+ return None
74
+ return ScrapeDoAmazonTool(api_token=token.strip())
75
+
76
+
77
+ # --------------------------------------------------------------- product (PDP)
78
+
79
+
80
+ def scrape_product(
81
+ token: str, query: str, geocode: str, zipcode: str, language: str
82
+ ) -> Tuple[str, List[str], Dict[str, Any], Optional[str]]:
83
+ tool = _tool_or_none(token)
84
+ if tool is None:
85
+ return NO_TOKEN_MD, [], {}, None
86
+ if not query or not query.strip():
87
+ return "⚠️ **Paste an Amazon product URL or ASIN.**", [], {}, None
88
+
89
+ data = tool.request("product", query, geocode, zipcode, language=language)
90
+ if data.get("status") != "success":
91
+ return _error_md(data), [], data, None
92
+
93
+ symbol = data.get("currency_symbol") or ""
94
+ code = data.get("currency") or ""
95
+ price = _money(data.get("price"), symbol, code)
96
+ list_price = data.get("list_price")
97
+
98
+ lines = [f"## {data.get('name') or 'Untitled product'}", ""]
99
+
100
+ facts = [
101
+ f"**ASIN** `{data.get('asin', '—')}`",
102
+ f"**Brand** {data.get('brand') or '—'}",
103
+ f"**Price** {price}",
104
+ ]
105
+ if list_price:
106
+ facts.append(f"**List price** ~~{_money(list_price, symbol, code)}~~")
107
+ if data.get("rating") is not None:
108
+ facts.append(
109
+ f"**Rating** {data.get('rating')} ★ ({data.get('total_ratings') or 0:,} ratings)"
110
+ )
111
+ facts.append("**Prime** " + ("yes" if data.get("is_prime") else "no"))
112
+ lines.append(" · ".join(facts))
113
+
114
+ shipping = data.get("shipping_info") or []
115
+ if shipping:
116
+ lines += ["", "**Delivery**"] + [f"- {item}" for item in shipping[:4]]
117
+
118
+ rankings = data.get("best_seller_rankings") or []
119
+ if rankings:
120
+ lines += ["", "**Best seller rankings**"]
121
+ for rank in rankings[:6]:
122
+ lines.append(f"- #{rank.get('rank')} in {rank.get('category')}")
123
+
124
+ details = data.get("technical_details") or {}
125
+ if isinstance(details, dict) and details:
126
+ lines += ["", "**Technical details**", "", "| Field | Value |", "| --- | --- |"]
127
+ for key, value in list(details.items())[:15]:
128
+ lines.append(f"| {key} | {value} |")
129
+
130
+ description = data.get("description")
131
+ if description:
132
+ lines += ["", "**Description**", "", str(description)[:1200]]
133
+
134
+ if data.get("url"):
135
+ lines += ["", f"[Open on Amazon →]({data['url']})"]
136
+
137
+ images = [
138
+ image.get("url")
139
+ for image in (data.get("images") or [])
140
+ if isinstance(image, dict) and image.get("url")
141
+ ]
142
+ if not images and data.get("thumbnail"):
143
+ images = [data["thumbnail"]]
144
+
145
+ flat = {
146
+ "asin": data.get("asin"),
147
+ "name": data.get("name"),
148
+ "brand": data.get("brand"),
149
+ "price": data.get("price"),
150
+ "list_price": data.get("list_price"),
151
+ "currency": data.get("currency"),
152
+ "rating": data.get("rating"),
153
+ "total_ratings": data.get("total_ratings"),
154
+ "is_prime": data.get("is_prime"),
155
+ "url": data.get("url"),
156
+ "thumbnail": data.get("thumbnail"),
157
+ }
158
+ csv_path = _write_csv([flat], f"amazon-product-{data.get('asin', 'result')}")
159
+
160
+ return "\n".join(lines), images[:12], data, csv_path
161
+
162
+
163
+ # ------------------------------------------------------------------- offers
164
+
165
+
166
+ OFFER_HEADERS = [
167
+ "Condition", "Seller", "Price", "Currency",
168
+ "Ships from", "FBA", "Prime", "Buy Box",
169
+ ]
170
+
171
+
172
+ def scrape_offers(
173
+ token: str, query: str, geocode: str, zipcode: str, language: str
174
+ ) -> Tuple[str, List[List[Any]], Dict[str, Any], Optional[str]]:
175
+ tool = _tool_or_none(token)
176
+ if tool is None:
177
+ return NO_TOKEN_MD, [], {}, None
178
+ if not query or not query.strip():
179
+ return "⚠️ **Paste an Amazon product URL or ASIN.**", [], {}, None
180
+
181
+ data = tool.request("offers", query, geocode, zipcode, language=language)
182
+ if data.get("status") != "success":
183
+ return _error_md(data), [], data, None
184
+
185
+ offers = data.get("offers") or []
186
+ if not offers:
187
+ return (
188
+ f"No competing offers returned for `{data.get('asin')}` in this "
189
+ "marketplace and delivery location. That is a valid result, not an "
190
+ "error — try another ZIP code or marketplace.",
191
+ [], data, None,
192
+ )
193
+
194
+ rows: List[List[Any]] = []
195
+ flat_rows: List[Dict[str, Any]] = []
196
+ for offer in offers:
197
+ listing = offer.get("listingPrice") or {}
198
+ prime = (offer.get("primeInformation") or {}).get("isPrime")
199
+ row = {
200
+ "asin": data.get("asin"),
201
+ "condition": offer.get("condition") or "",
202
+ "seller": offer.get("merchantName") or "",
203
+ "price": listing.get("amount", ""),
204
+ "currency": listing.get("currency", ""),
205
+ "ships_from": offer.get("shipsFrom") or "",
206
+ "fulfilled_by_amazon": bool(offer.get("isFulfilledByAmazon")),
207
+ "is_prime": bool(prime),
208
+ "is_buy_box_winner": bool(offer.get("isBuyBoxWinner")),
209
+ }
210
+ flat_rows.append(row)
211
+ rows.append([
212
+ row["condition"], row["seller"], row["price"], row["currency"],
213
+ row["ships_from"],
214
+ "✓" if row["fulfilled_by_amazon"] else "",
215
+ "✓" if row["is_prime"] else "",
216
+ "✓" if row["is_buy_box_winner"] else "",
217
+ ])
218
+
219
+ prices = [
220
+ offer["price"] for offer in flat_rows
221
+ if isinstance(offer["price"], (int, float))
222
+ ]
223
+ summary = f"**{len(rows)} offer(s)** for ASIN `{data.get('asin')}`"
224
+ if prices:
225
+ summary += f" · lowest {min(prices)} · highest {max(prices)}"
226
+ buy_box = next((o["seller"] for o in flat_rows if o["is_buy_box_winner"]), None)
227
+ if buy_box:
228
+ summary += f" · Buy Box: **{buy_box}**"
229
+
230
+ csv_path = _write_csv(flat_rows, f"amazon-offers-{data.get('asin', 'result')}")
231
+ return summary, rows, data, csv_path
232
+
233
+
234
+ # ------------------------------------------------------------------- search
235
+
236
+
237
+ SEARCH_HEADERS = [
238
+ "#", "ASIN", "Title", "Price", "Rating", "Reviews", "Prime", "Sponsored", "Badge",
239
+ ]
240
+
241
+
242
+ def scrape_search(
243
+ token: str, keyword: str, geocode: str, zipcode: str, page: int, language: str
244
+ ) -> Tuple[str, List[List[Any]], Dict[str, Any], Optional[str]]:
245
+ tool = _tool_or_none(token)
246
+ if tool is None:
247
+ return NO_TOKEN_MD, [], {}, None
248
+ if not keyword or not keyword.strip():
249
+ return "⚠️ **Enter a search keyword.**", [], {}, None
250
+
251
+ data = tool.request("search", keyword, geocode, zipcode, page=page, language=language)
252
+ if data.get("status") != "success":
253
+ return _error_md(data), [], data, None
254
+
255
+ products = data.get("products") or []
256
+ if not products:
257
+ return "No products returned for that keyword.", [], data, None
258
+
259
+ rows: List[List[Any]] = []
260
+ flat_rows: List[Dict[str, Any]] = []
261
+ for product in products:
262
+ price = product.get("price") or {}
263
+ rating = product.get("rating") or {}
264
+ row = {
265
+ "position": product.get("position"),
266
+ "asin": product.get("asin"),
267
+ "title": product.get("title"),
268
+ "price": price.get("amount", ""),
269
+ "currency": price.get("currencyCode", ""),
270
+ "rating": rating.get("value", ""),
271
+ "rating_count": rating.get("count", ""),
272
+ "review_count": product.get("reviewCount", ""),
273
+ "is_prime": bool(product.get("isPrime")),
274
+ "is_sponsored": bool(product.get("isSponsored")),
275
+ "badge": product.get("badge") or "",
276
+ "url": product.get("url"),
277
+ "image_url": product.get("imageUrl"),
278
+ }
279
+ flat_rows.append(row)
280
+ title = row["title"] or ""
281
+ rows.append([
282
+ row["position"], row["asin"],
283
+ title[:90] + ("…" if len(title) > 90 else ""),
284
+ f"{row['price']} {row['currency']}".strip(),
285
+ row["rating"], row["review_count"],
286
+ "✓" if row["is_prime"] else "",
287
+ "✓" if row["is_sponsored"] else "",
288
+ row["badge"],
289
+ ])
290
+
291
+ sponsored = sum(1 for product in flat_rows if product["is_sponsored"])
292
+ summary = (
293
+ f"**{len(rows)} results** for “{data.get('keyword')}” · page {data.get('page')} · "
294
+ f"{sponsored} sponsored, {len(rows) - sponsored} organic"
295
+ )
296
+ if data.get("totalResults"):
297
+ summary += f" · {data['totalResults']}"
298
+
299
+ csv_path = _write_csv(flat_rows, "amazon-search")
300
+ return summary, rows, data, csv_path
301
+
302
+
303
+ # ----------------------------------------------------------------------- UI
304
+
305
+
306
+ HEADER_MD = f"""
307
+ # 📦 Amazon Product Scraper
308
+
309
+ **Pull structured JSON from any Amazon marketplace — product pages, every seller
310
+ offer, and keyword search results.** No HTML parsing, no ASIN spreadsheets, no blocks.
311
+
312
+ AWS WAF bypass, proxy rotation, session handling and CAPTCHAs are handled for you
313
+ across 21 marketplaces, with ZIP-code level delivery targeting.
314
+ Powered by [Scrape.do](https://scrape.do/).
315
+
316
+ ### 🔑 Need an API token?
317
+ 👉 **[Sign up free on Scrape.do]({SCRAPE_DO_SIGNUP_URL})** — 1,000 free requests / month, no credit card.
318
+ """
319
+
320
+ FOOTER_MD = f"""
321
+ ---
322
+
323
+ ### Using this as a smolagents Tool
324
+
325
+ ```python
326
+ from smolagents import CodeAgent, InferenceClientModel
327
+ from tool import ScrapeDoAmazonTool
328
+
329
+ agent = CodeAgent(
330
+ tools=[ScrapeDoAmazonTool(api_token="YOUR_SCRAPEDO_TOKEN")],
331
+ model=InferenceClientModel(),
332
+ )
333
+ agent.run("Compare the price and Buy Box seller for ASIN B0BLRJ4R8F in the US and the UK")
334
+ ```
335
+
336
+ Or set `SCRAPE_DO_API_TOKEN` in your environment and instantiate without args.
337
+
338
+ Only publicly available product data is in scope. Anything behind an Amazon login —
339
+ account pages, full customer review archives — is out of bounds; see the
340
+ [Amazon scraping guide](https://scrape.do/blog/amazon-scraping/) for the legal and
341
+ ethical boundaries.
342
+
343
+ [Scrape.do](https://scrape.do/) · [Amazon Scraper API docs](https://scrape.do/documentation/amazon-scraper-api/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL})
344
+ """
345
+
346
+ ZIP_INFO = (
347
+ "ZIP code for us / gb / de / fr / it / es / ca / jp / in. "
348
+ "For other marketplaces, enter a delivery country name instead (or leave blank)."
349
+ )
350
+
351
+
352
+ def build_demo() -> gr.Blocks:
353
+ with gr.Blocks(title="Amazon Product Scraper — Scrape.do") as demo:
354
+ gr.Markdown(HEADER_MD)
355
+
356
+ api_token = gr.Textbox(
357
+ label="Scrape.do API Token",
358
+ placeholder="Paste your token here…",
359
+ type="password",
360
+ info="Don't have one? Get a free token from the link above.",
361
+ )
362
+
363
+ with gr.Row():
364
+ geocode = gr.Dropdown(
365
+ label="Marketplace",
366
+ choices=MARKET_CHOICES,
367
+ value="us",
368
+ )
369
+ zipcode = gr.Textbox(
370
+ label="Delivery location",
371
+ placeholder="10001",
372
+ info=ZIP_INFO,
373
+ )
374
+ language = gr.Textbox(
375
+ label="Language",
376
+ placeholder="EN",
377
+ info="Optional ISO 639-1 code, uppercase. Must be supported by the marketplace.",
378
+ )
379
+
380
+ with gr.Tabs():
381
+ # ------------------------------------------------ product tab
382
+ with gr.Tab("Product page"):
383
+ gr.Markdown(
384
+ "Paste a product URL or a bare ASIN. Returns title, brand, price, "
385
+ "list price, rating, images, best seller rankings and specs."
386
+ )
387
+ product_query = gr.Textbox(
388
+ label="Amazon product URL or ASIN",
389
+ placeholder="https://www.amazon.com/dp/B0BLRJ4R8F · or just B0BLRJ4R8F",
390
+ )
391
+ product_btn = gr.Button("Scrape product", variant="primary")
392
+
393
+ product_summary = gr.Markdown()
394
+ product_gallery = gr.Gallery(
395
+ label="Product images", columns=6, height=180, preview=False
396
+ )
397
+ product_csv = gr.File(label="Download CSV")
398
+ with gr.Accordion("Raw JSON response", open=False):
399
+ product_json = gr.JSON()
400
+
401
+ product_btn.click(
402
+ fn=scrape_product,
403
+ inputs=[api_token, product_query, geocode, zipcode, language],
404
+ outputs=[product_summary, product_gallery, product_json, product_csv],
405
+ )
406
+
407
+ # ------------------------------------------------- offers tab
408
+ with gr.Tab("Seller offers"):
409
+ gr.Markdown(
410
+ "Every active offer on an ASIN: price, condition, seller, "
411
+ "fulfilment and who currently holds the Buy Box."
412
+ )
413
+ offers_query = gr.Textbox(
414
+ label="Amazon product URL or ASIN",
415
+ placeholder="B0DZDBWM5B",
416
+ )
417
+ offers_btn = gr.Button("Scrape offers", variant="primary")
418
+
419
+ offers_summary = gr.Markdown()
420
+ offers_table = gr.Dataframe(
421
+ headers=OFFER_HEADERS, wrap=True, label="Offers"
422
+ )
423
+ offers_csv = gr.File(label="Download CSV")
424
+ with gr.Accordion("Raw JSON response", open=False):
425
+ offers_json = gr.JSON()
426
+
427
+ offers_btn.click(
428
+ fn=scrape_offers,
429
+ inputs=[api_token, offers_query, geocode, zipcode, language],
430
+ outputs=[offers_summary, offers_table, offers_json, offers_csv],
431
+ )
432
+
433
+ # ------------------------------------------------- search tab
434
+ with gr.Tab("Search results"):
435
+ gr.Markdown(
436
+ "Keyword and category search with organic vs. sponsored "
437
+ "placements and exact on-page positions."
438
+ )
439
+ with gr.Row():
440
+ search_query = gr.Textbox(
441
+ label="Search keyword",
442
+ placeholder="laptop stands",
443
+ scale=3,
444
+ )
445
+ search_page = gr.Number(
446
+ label="Page", value=1, precision=0, minimum=1, scale=1
447
+ )
448
+ search_btn = gr.Button("Scrape search results", variant="primary")
449
+
450
+ search_summary = gr.Markdown()
451
+ search_table = gr.Dataframe(
452
+ headers=SEARCH_HEADERS, wrap=True, label="Results"
453
+ )
454
+ search_csv = gr.File(label="Download CSV")
455
+ with gr.Accordion("Raw JSON response", open=False):
456
+ search_json = gr.JSON()
457
+
458
+ search_btn.click(
459
+ fn=scrape_search,
460
+ inputs=[api_token, search_query, geocode, zipcode, search_page, language],
461
+ outputs=[search_summary, search_table, search_json, search_csv],
462
+ )
463
+
464
+ gr.Markdown(FOOTER_MD)
465
+
466
+ return demo
467
+
468
+
469
+ if __name__ == "__main__":
470
+ build_demo().launch()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio
2
+ requests
3
+ smolagents
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)