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
@spaces.GPU(duration=1)
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'{_esc(text)}'
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'{title}' 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'{_esc(l.get("status"))}' if l.get("status") else ""
cards.append(f'
{_esc(l.get("price_text")) or _muted("No price")}{status}
'
f'
{title}
{spec}
'
f'
{_esc(l.get("agency"))}
')
if not cards:
cards.append('Nothing came back.
')
return f''
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'{k}
{v}
' for k, v in rows)
button = f'View on Domain' if link else ""
return (f'{_esc(d.get("headline") or d.get("address"))}
'
f'
{specs}
Description
'
f'{_esc((d.get("description") or "")[:1200])}
{button}
')
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 = """
"""
HERO = f"""
Domain.com.au Scraper
Australian property listings as data. 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.
Domain answers scripts with 403 Access Denied. Each page goes through
Scrape.do
with residential proxies, and the data comes from the page's __NEXT_DATA__.
Get a free API token →
Bondi Beach · sold · live test
Sold listings16,626
Per page20
Credits per page10
"""
CREDIT_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.
"""
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/-")
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)