Spaces:
Sleeping
Sleeping
Download app.py from bugrahans/domain-com-au-scraper: direct link, hf CLI and curl.
- Browser
- Download file 16.1 kB
-
https://huggingface.co/spaces/bugrahans/domain-com-au-scraper/resolve/main/app.py
- Command line
-
hf download hf://spaces/bugrahans/domain-com-au-scraper/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bugrahans/domain-com-au-scraper/resolve/main/app.py
16.1 kB
| from __future__ import annotations | |
| import csv | |
| import html | |
| import tempfile | |
| from typing import Any, Dict, List, Optional | |
| import gradio as gr | |
| from tool import DEFAULT_SUBURB, SCRAPE_DO_SIGNUP_URL, ScrapeDoDomainTool | |
| # ZeroGPU hardware refuses to keep a Space alive unless it finds at least one | |
| # @spaces.GPU function at startup. This app never touches a GPU; the probe is never called. | |
| try: | |
| import spaces | |
| def _zerogpu_probe() -> str: | |
| return "ok" | |
| except ImportError: | |
| pass | |
| NO_TOKEN_MD = ( | |
| "### Paste your Scrape.do API token above\n\n" | |
| f"No token yet? [Create a free account]({SCRAPE_DO_SIGNUP_URL}) — " | |
| "1,000 free credits a month, no credit card. Every Domain page costs 10 credits." | |
| ) | |
| def _esc(value: Any) -> str: | |
| return html.escape("" if value is None else str(value), quote=True) | |
| def _safe_link(url: Any) -> str: | |
| url = str(url or "") | |
| return url if url.startswith("https://www.domain.com.au/") else "" | |
| def _tool_or_none(token: str) -> Optional[ScrapeDoDomainTool]: | |
| if not token or not token.strip(): | |
| return None | |
| return ScrapeDoDomainTool(api_token=token.strip()) | |
| def _write_csv(rows: List[Dict[str, Any]], prefix: str) -> Optional[str]: | |
| if not rows: | |
| return None | |
| fieldnames: List[str] = [] | |
| for row in rows: | |
| for key in row: | |
| if key not in fieldnames: | |
| fieldnames.append(key) | |
| handle = tempfile.NamedTemporaryFile( | |
| mode="w", suffix=".csv", prefix=f"{prefix}-", delete=False, newline="", encoding="utf-8-sig", | |
| ) | |
| writer = csv.DictWriter(handle, fieldnames=fieldnames, extrasaction="ignore") | |
| writer.writeheader() | |
| for row in rows: | |
| flat = {} | |
| for k, v in row.items(): | |
| if isinstance(v, list): | |
| flat[k] = " | ".join(x.get("name", "") if isinstance(x, dict) else str(x) for x in v) | |
| elif isinstance(v, dict): | |
| flat[k] = " | ".join(f"{a}: {b}" for a, b in v.items()) | |
| else: | |
| flat[k] = v | |
| writer.writerow(flat) | |
| handle.close() | |
| return handle.name | |
| def _error_md(data: Dict[str, Any]) -> str: | |
| out = f"**That didn't go through.**\n\n{data.get('errorMessage') or 'Unknown error'}" | |
| if data.get("hint"): | |
| out += f"\n\n{data['hint']}" | |
| if data.get("credits_used"): | |
| out += f"\n\n{data['credits_used']} credits used." | |
| return out | |
| def _muted(text: str = "Not listed") -> str: | |
| return f'<span class="sp-muted">{_esc(text)}</span>' | |
| def _eur(value: Any) -> str: | |
| if value in (None, ""): | |
| return "" | |
| return f"{float(value):,.2f} €".replace(",", "X").replace(".", ",").replace("X", ".") | |
| def _money(v: Any) -> str: | |
| return f"${int(v):,}" if v not in (None, "") else "" | |
| def render_listings(listings: List[Dict[str, Any]]) -> str: | |
| cards = [] | |
| for l in listings: | |
| link = _safe_link(l.get("url")) | |
| title = _esc(l.get("address")) | |
| title = f'<a href="{_esc(link)}" target="_blank" rel="noopener noreferrer">{title}</a>' if link else title | |
| spec = " · ".join(x for x in [f"{l['beds']} bd" if l.get("beds") is not None else "", f"{l['baths']} ba" if l.get("baths") is not None else "", | |
| f"{l['parking']} car" if l.get("parking") is not None else "", _esc(l.get("property_type"))] if x) | |
| status = f'<span class="sp-age">{_esc(l.get("status"))}</span>' if l.get("status") else "" | |
| cards.append(f'<div class="sp-card"><div class="sp-card-top"><span class="sp-name">{_esc(l.get("price_text")) or _muted("No price")}</span>{status}</div>' | |
| f'<div style="margin-top:4px">{title}</div><div class="sp-muted" style="font-size:.85rem;margin-top:4px">{spec}</div>' | |
| f'<div class="sp-muted" style="font-size:.8rem;margin-top:2px">{_esc(l.get("agency"))}</div></div>') | |
| if not cards: | |
| cards.append('<div class="sp-empty">Nothing came back.</div>') | |
| return f'<div class="sp-wrap"><div class="sp-grid">{"".join(cards)}</div></div>' | |
| def render_detail(d: Dict[str, Any]) -> str: | |
| link = _safe_link(d.get("url")) | |
| rows = [("Price", _esc(d.get("title")) or _muted()), ("Type", _esc(d.get("property_type")) or _muted()), | |
| ("Beds · baths · parking", _esc(f"{d.get('beds')} · {d.get('baths')} · {d.get('parking')}")), | |
| ("Address", _esc(d.get("address")) or _muted()), ("Agency", _esc(d.get("agency")) or _muted()), | |
| ("Listed", _esc((d.get("created_on") or "")[:10]) or _muted()), | |
| ("Suburb median price", _esc(_money(d.get("suburb_median_price"))) or _muted()), | |
| ("Suburb median rent / wk", _esc(_money(d.get("suburb_median_rent"))) or _muted()), | |
| ("Days on market (suburb)", _esc(d.get("suburb_days_on_market")) if d.get("suburb_days_on_market") is not None else _muted()), | |
| ("Auction clearance (suburb)", (_esc(d.get("suburb_auction_clearance")) + "%") if d.get("suburb_auction_clearance") is not None else _muted()), | |
| ("Features", _esc(", ".join(d.get("features") or [])) or _muted())] | |
| specs = "".join(f'<div class="sp-spec-name">{k}</div><div class="sp-spec-value">{v}</div>' for k, v in rows) | |
| button = f'<a class="sp-btn" href="{_esc(link)}" target="_blank" rel="noopener noreferrer">View on Domain</a>' if link else "" | |
| return (f'<div class="sp-wrap"><div class="sp-profile"><div class="sp-p-name">{_esc(d.get("headline") or d.get("address"))}</div>' | |
| f'<div class="sp-specs">{specs}</div><div class="sp-sub">Description</div><div class="sp-muted" style="white-space:pre-wrap">' | |
| f'{_esc((d.get("description") or "")[:1200])}</div>{button}</div></div>') | |
| def run_search(token: str, suburb: str, mode: str, page: float): | |
| tool = _tool_or_none(token) | |
| if tool is None: | |
| return NO_TOKEN_MD, "", {}, None | |
| data = tool.search(suburb, mode, int(page or 1)) | |
| if data.get("status") != "success": | |
| return _error_md(data), "", data, None | |
| ls = data.get("listings") or [] | |
| summary = (f"**{len(ls)}** listings on page {data.get('page')} of {data.get('total_pages')} · **{data.get('total_listings'):,}** " | |
| f"{_esc(mode)} listings in {_esc(suburb)}\n\nCopy a listing link into the **Listing** tab for the full page. " | |
| f"1 request · {data.get('credits_used')} credits") | |
| return summary, render_listings(ls), data, _write_csv(ls, "domain-search") | |
| def run_listing(token: str, url: str): | |
| tool = _tool_or_none(token) | |
| if tool is None: | |
| return NO_TOKEN_MD, "", {}, None | |
| data = tool.listing(url) | |
| if data.get("status") != "success": | |
| return _error_md(data), "", data, None | |
| d = data["listing"] | |
| summary = f"**{_esc(d.get('title'))}** · {len(d.get('features') or [])} features · {len(d.get('images') or [])} photos\n\n1 request · {data.get('credits_used')} credits" | |
| return summary, render_detail(d), data, _write_csv([d], "domain-listing") | |
| STYLE = """ | |
| <style> | |
| .gradio-container, .gradio-container button, .gradio-container input, | |
| .gradio-container textarea, .gradio-container select { | |
| font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif; | |
| } | |
| .sp-hero { position: relative; overflow: hidden; border-radius: 18px; padding: 30px 32px 28px 32px; margin-bottom: 16px; | |
| background: radial-gradient(circle at 92% 12%, rgba(14,168,0,.45) 0%, rgba(14,168,0,0) 45%), | |
| linear-gradient(135deg, #043300 0%, #086300 60%, #0b8a00 100%); } | |
| .sp-hero, .sp-hero * { color: #ffffff !important; } | |
| .sp-hero-inner { position: relative; z-index: 1; max-width: 640px; } | |
| .sp-hero h1 { font-size: 2.05rem !important; font-weight: 800 !important; margin: 0 0 10px 0 !important; } | |
| .sp-hero h1 span { color: #8ff07f !important; } | |
| .sp-hero p { margin: 0 0 8px 0 !important; font-size: 1rem !important; line-height: 1.55 !important; opacity: .96; } | |
| .sp-hero a { text-decoration: underline !important; } | |
| .sp-hero a.sp-cta { display: inline-block; margin-top: 12px; padding: 11px 24px; border-radius: 10px; | |
| background: #ffc400 !important; color: #043300 !important; font-weight: 800 !important; text-decoration: none !important; } | |
| .sp-hero-card { position: absolute; right: 34px; top: 50%; transform: translateY(-50%); width: 270px; z-index: 1; | |
| background: #ffffff; border-radius: 14px; padding: 14px 16px; box-shadow: 0 10px 28px rgba(0,0,0,.35); } | |
| .sp-hero-card, .sp-hero-card * { color: #212529 !important; } | |
| .sp-hc-title { font-size: .72rem; font-weight: 800; color: #6c757d !important; text-transform: uppercase; letter-spacing: .05em; margin-bottom: 8px; } | |
| .sp-hc-row { display: grid; grid-template-columns: 1fr auto; gap: 8px; font-size: .84rem; margin: 7px 0; } | |
| .sp-hc-row b { color: #0b8a00 !important; } | |
| @media (max-width: 900px) { .sp-hero-card { display: none; } } | |
| .sp-note { border-left: 3px solid #0b8a00; background: #ecf9ea; padding: 12px 16px; border-radius: 0 10px 10px 0; | |
| font-size: .9rem; margin-bottom: 12px; color: #212529 !important; } | |
| .gradio-container .primary, .gradio-container button.primary, .gradio-container button[variant="primary"] { | |
| background: #0b8a00 !important; background-image: none !important; border-color: #0b8a00 !important; | |
| color: #ffffff !important; border-radius: 10px !important; font-weight: 800 !important; } | |
| .gradio-container .primary:hover, .gradio-container button.primary:hover, | |
| .gradio-container button[variant="primary"]:hover { background: #086300 !important; } | |
| .sp-wrap { color: #212529 !important; } | |
| .sp-muted { color: #6c757d !important; } | |
| .sp-empty { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 12px; padding: 20px; color: #6c757d !important; } | |
| .sp-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(280px, 100%), 1fr)); gap: 10px; } | |
| .sp-card { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 12px; padding: 10px 14px; } | |
| .sp-card-top { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; } | |
| .sp-name a, .sp-name { font-weight: 700; color: #212529 !important; text-decoration: none !important; } | |
| .sp-name a:hover { color: #0b8a00 !important; text-decoration: underline !important; } | |
| .sp-age { background: #ecf9ea; color: #086300 !important; font-weight: 800; font-size: .7rem; border-radius: 6px; padding: 2px 8px; white-space: nowrap; } | |
| .sp-profile { background: #ffffff; border: 1px solid #e8e8e8; border-radius: 16px; padding: 18px 22px; } | |
| .sp-p-name { font-size: 1.4rem; font-weight: 800; color: #212529 !important; } | |
| .sp-specs { display: grid; grid-template-columns: minmax(140px, .35fr) 1fr; border-top: 1px solid #ececec; margin-top: 12px; } | |
| .sp-spec-name, .sp-spec-value { padding: 8px 10px; border-bottom: 1px solid #ececec; font-size: .86rem; } | |
| .sp-spec-name { color: #6c757d !important; } | |
| .sp-spec-value { color: #212529 !important; } | |
| .sp-sub { font-weight: 800; margin: 16px 0 6px 0; color: #212529 !important; } | |
| .sp-chip { display: inline-block; background: #f5f6f8; border: 1px solid #e8e8e8; border-radius: 6px; padding: 2px 8px; margin: 2px 4px 2px 0; font-size: .8rem; color: #212529 !important; } | |
| .sp-event { border-left: 3px solid #0b8a00; padding: 4px 10px; margin: 6px 0; font-size: .85rem; color: #212529 !important; } | |
| .sp-date { color: #0b8a00 !important; font-weight: 700; } | |
| .sp-btn { display: inline-block; margin-top: 14px; padding: 10px 22px; border-radius: 10px; background: #0b8a00 !important; | |
| color: #ffffff !important; font-weight: 800; text-decoration: none !important; font-size: .9rem; } | |
| footer { display: none !important; } | |
| </style> | |
| """ | |
| HERO = f""" | |
| <div class="sp-hero"> | |
| <div class="sp-hero-inner"> | |
| <h1>Domain.com.au <span>Scraper</span></h1> | |
| <p><strong>Australian property listings as data.</strong> Search any suburb for sale, for rent or sold: price, status and | |
| sale date, beds, baths, parking, land size, address, agency. Open a listing for its description, features and Domain's suburb medians.</p> | |
| <p>Domain answers scripts with <em>403 Access Denied</em>. Each page goes through | |
| <a href="https://scrape.do/?utm_source=huggingface&utm_medium=domain-com-au-scraper" target="_blank" rel="noopener noreferrer">Scrape.do</a> | |
| with residential proxies, and the data comes from the page's __NEXT_DATA__.</p> | |
| <a class="sp-cta" href="{SCRAPE_DO_SIGNUP_URL}" target="_blank" rel="noopener noreferrer">Get a free API token →</a> | |
| </div> | |
| <div class="sp-hero-card" aria-hidden="true"> | |
| <div class="sp-hc-title">Bondi Beach · sold · live test</div> | |
| <div class="sp-hc-row"><span>Sold listings</span><span><b>16,626</b></span></div> | |
| <div class="sp-hc-row"><span>Per page</span><span><b>20</b></span></div> | |
| <div class="sp-hc-row"><span>Credits per page</span><span><b>10</b></span></div> | |
| </div> | |
| </div> | |
| """ | |
| CREDIT_NOTE = """ | |
| <div class="sp-note"> | |
| Every page is one Scrape.do request with super=true: 10 credits. The free 1,000 credits a month cover 100 pages, about 2,000 listings. | |
| Agents are real people: use their details only for legitimate purposes. | |
| </div> | |
| """ | |
| FOOTER_MD = f""" | |
| --- | |
| ### Use it as a smolagents Tool | |
| ```python | |
| from smolagents import CodeAgent, InferenceClientModel | |
| from tool import ScrapeDoDomainTool | |
| agent = CodeAgent(tools=[ScrapeDoDomainTool(api_token="YOUR_SCRAPEDO_TOKEN")], model=InferenceClientModel()) | |
| agent.run("What did 2-bedroom apartments sell for in {DEFAULT_SUBURB} recently?") | |
| ``` | |
| Prefer plain Python? `pip install domain-com-au-scraper` ([GitHub](https://github.com/bugrahansss/domain-com-au-scraper)) · | |
| No-code: [Apify actor](https://apify.com/scrapedo/domain-com-au-scraper) | |
| [Scrape.do](https://scrape.do/?utm_source=huggingface&utm_medium=domain-com-au-scraper) · [Documentation](https://scrape.do/documentation/) · [Sign up free]({SCRAPE_DO_SIGNUP_URL}) | |
| """ | |
| def build_demo() -> gr.Blocks: | |
| with gr.Blocks(title="Domain.com.au Scraper — Scrape.do") as demo: | |
| gr.HTML(STYLE) | |
| gr.HTML(HERO) | |
| api_token = gr.Textbox(label="Scrape.do API token", placeholder="Paste your token here", type="password", | |
| info="Free tier: 1,000 credits a month. 10 credits per Domain page.") | |
| gr.HTML(CREDIT_NOTE) | |
| with gr.Tabs(): | |
| with gr.Tab("Search a suburb"): | |
| with gr.Row(): | |
| suburb = gr.Textbox(label="Suburb, state and postcode", value=DEFAULT_SUBURB, scale=4) | |
| mode = gr.Dropdown(choices=["sale", "rent", "sold"], value="sold", label="Listings", scale=1) | |
| page = gr.Number(label="Page", value=1, minimum=1, maximum=50, precision=0, scale=1) | |
| s_btn = gr.Button("Search", variant="primary") | |
| s_sum, s_view = gr.Markdown(), gr.HTML() | |
| s_csv = gr.File(label="Download as CSV") | |
| with gr.Accordion("Raw JSON response", open=False): | |
| s_json = gr.JSON() | |
| with gr.Tab("Listing"): | |
| url = gr.Textbox(label="Domain listing URL", placeholder="https://www.domain.com.au/<address>-<listingId>") | |
| l_btn = gr.Button("Open listing", variant="primary") | |
| l_sum, l_view = gr.Markdown(), gr.HTML() | |
| l_csv = gr.File(label="Download as CSV") | |
| with gr.Accordion("Raw JSON response", open=False): | |
| l_json = gr.JSON() | |
| s_btn.click(fn=run_search, inputs=[api_token, suburb, mode, page], outputs=[s_sum, s_view, s_json, s_csv]) | |
| suburb.submit(fn=run_search, inputs=[api_token, suburb, mode, page], outputs=[s_sum, s_view, s_json, s_csv]) | |
| l_btn.click(fn=run_listing, inputs=[api_token, url], outputs=[l_sum, l_view, l_json, l_csv]) | |
| url.submit(fn=run_listing, inputs=[api_token, url], outputs=[l_sum, l_view, l_json, l_csv]) | |
| gr.Markdown(FOOTER_MD) | |
| return demo | |
| # Hugging Face Spaces launches the module-level `demo` object rather than calling launch() itself. | |
| demo = build_demo() | |
| if __name__ == "__main__": | |
| demo.queue(default_concurrency_limit=4).launch(ssr_mode=False) | |