blocket-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """Fast CLI for searching Blocket.se — optimized for agents and scripting."""
2
+
3
+ __version__ = "0.1.0"
blocket_cli/api.py ADDED
@@ -0,0 +1,159 @@
1
+ """Blocket.se search API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from html.parser import HTMLParser
7
+
8
+ import httpx
9
+
10
+ BASE = "https://www.blocket.se"
11
+ SEARCH_URL = f"{BASE}/recommerce/forsale/search/api/search/SEARCH_ID_BAP_COMMON"
12
+
13
+ HEADERS = {
14
+ "User-Agent": "blocket-cli/0.1.0 (https://github.com/lennart-johansson/blocket-cli)",
15
+ }
16
+
17
+ LOCATIONS = {
18
+ "blekinge": "0.300010",
19
+ "dalarna": "0.300020",
20
+ "gotland": "0.300009",
21
+ "gavleborg": "0.300021",
22
+ "halland": "0.300013",
23
+ "jamtland": "0.300023",
24
+ "jonkoping": "0.300006",
25
+ "kalmar": "0.300008",
26
+ "kronoberg": "0.300007",
27
+ "norrbotten": "0.300025",
28
+ "skane": "0.300012",
29
+ "stockholm": "0.300001",
30
+ "sodermanland": "0.300004",
31
+ "uppsala": "0.300003",
32
+ "varmland": "0.300017",
33
+ "vasterbotten": "0.300024",
34
+ "vasternorrland": "0.300022",
35
+ "vastmanland": "0.300019",
36
+ "vastra-gotaland": "0.300014",
37
+ "orebro": "0.300018",
38
+ "ostergotland": "0.300005",
39
+ }
40
+
41
+ CATEGORIES = {
42
+ "business": "0.91",
43
+ "home-garden": "0.67",
44
+ "pets": "0.77",
45
+ "electronics": "0.93",
46
+ "vehicle-parts": "0.90",
47
+ "family": "0.68",
48
+ "fashion": "0.71",
49
+ "art": "0.76",
50
+ "furniture": "0.78",
51
+ "sports": "0.69",
52
+ "hobby": "0.86",
53
+ }
54
+
55
+ # Swedish display names for categories
56
+ CATEGORY_LABELS = {
57
+ "business": "Affärsverksamhet",
58
+ "home-garden": "Bygg och trädgård",
59
+ "pets": "Djur och tillbehör",
60
+ "electronics": "Elektronik och vitvaror",
61
+ "vehicle-parts": "Fordonstillbehör",
62
+ "family": "Föräldrar och barn",
63
+ "fashion": "Kläder, kosmetika och accessoarer",
64
+ "art": "Konst och antikt",
65
+ "furniture": "Möbler och inredning",
66
+ "sports": "Sport och friluftsliv",
67
+ "hobby": "Underhållning och hobby",
68
+ }
69
+
70
+
71
+ def _resolve_location(name: str) -> str:
72
+ code = LOCATIONS.get(name.lower())
73
+ if not code:
74
+ raise ValueError(f"Unknown location '{name}'. Valid: {', '.join(sorted(LOCATIONS))}")
75
+ return code
76
+
77
+
78
+ def _resolve_category(name: str) -> str:
79
+ code = CATEGORIES.get(name.lower())
80
+ if not code:
81
+ raise ValueError(f"Unknown category '{name}'. Valid: {', '.join(sorted(CATEGORIES))}")
82
+ return code
83
+
84
+
85
+ def search(
86
+ query: str,
87
+ *,
88
+ location: str | None = None,
89
+ category: str | None = None,
90
+ price_min: int | None = None,
91
+ price_max: int | None = None,
92
+ sort: str | None = None,
93
+ page: int = 1,
94
+ ) -> dict:
95
+ """Search listings on Blocket."""
96
+ params: list[tuple[str, str]] = [("q", query), ("page", str(page))]
97
+ if location:
98
+ params.append(("location", _resolve_location(location)))
99
+ if category:
100
+ params.append(("category", _resolve_category(category)))
101
+ if price_min is not None:
102
+ params.append(("price_from", str(price_min)))
103
+ if price_max is not None:
104
+ params.append(("price_to", str(price_max)))
105
+ if sort:
106
+ params.append(("sort", sort))
107
+
108
+ r = httpx.get(SEARCH_URL, params=params, headers=HEADERS, timeout=15, follow_redirects=True)
109
+ r.raise_for_status()
110
+ return r.json()
111
+
112
+
113
+ def get_ad(ad_id: int | str) -> dict:
114
+ """Fetch full ad details from the item page's structured data."""
115
+ # Try recommerce first (most common), fall back to mobility
116
+ for path in ("recommerce/forsale/item", "mobility/item"):
117
+ url = f"{BASE}/{path}/{ad_id}"
118
+ r = httpx.get(url, headers=HEADERS, timeout=15, follow_redirects=True)
119
+ if r.status_code == 200:
120
+ result = _extract_product_data(r.text)
121
+ if result:
122
+ return result
123
+
124
+ return {"error": f"Could not find ad {ad_id}"}
125
+
126
+
127
+ def _extract_product_data(html: str) -> dict | None:
128
+ """Extract JSON-LD Product data from HTML."""
129
+
130
+ class _LDJsonExtractor(HTMLParser):
131
+ def __init__(self):
132
+ super().__init__()
133
+ self._capture = False
134
+ self.scripts: list[str] = []
135
+
136
+ def handle_starttag(self, tag, attrs):
137
+ if tag == "script" and dict(attrs).get("type") == "application/ld+json":
138
+ self._capture = True
139
+
140
+ def handle_data(self, data):
141
+ if self._capture:
142
+ self.scripts.append(data)
143
+
144
+ def handle_endtag(self, tag):
145
+ if tag == "script":
146
+ self._capture = False
147
+
148
+ parser = _LDJsonExtractor()
149
+ parser.feed(html)
150
+
151
+ for script in parser.scripts:
152
+ try:
153
+ data = json.loads(script)
154
+ if isinstance(data, dict) and data.get("@type") == "Product":
155
+ return data
156
+ except json.JSONDecodeError:
157
+ continue
158
+
159
+ return None
blocket_cli/cli.py ADDED
@@ -0,0 +1,111 @@
1
+ """Blocket CLI — search Blocket.se from the terminal."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ import click
8
+
9
+ from . import api, format
10
+
11
+
12
+ @click.group()
13
+ @click.version_option()
14
+ def main():
15
+ """Search Blocket.se from the command line.
16
+
17
+ Fast, minimal CLI for searching Sweden's largest marketplace.
18
+ Designed for scripting, agents, and quick lookups.
19
+ """
20
+ pass
21
+
22
+
23
+ @main.command()
24
+ @click.argument("query")
25
+ @click.option("-l", "--location", help="County filter (e.g. stockholm, skane)")
26
+ @click.option("-c", "--category", help="Category filter (use 'blocket categories' to list)")
27
+ @click.option("--price-min", type=int, help="Minimum price (SEK)")
28
+ @click.option("--price-max", type=int, help="Maximum price (SEK)")
29
+ @click.option(
30
+ "--sort",
31
+ type=click.Choice(["relevance", "price-asc", "price-desc", "date"], case_sensitive=False),
32
+ help="Sort order",
33
+ )
34
+ @click.option("-n", "--limit", type=int, help="Max results to show")
35
+ @click.option("-p", "--page", type=int, default=1, help="Page number")
36
+ @click.option("-o", "--output", type=click.Choice(["table", "json", "jsonl"]), default="table", help="Output format")
37
+ @click.option("--raw", is_flag=True, help="Full API response (default: slim agent-friendly fields)")
38
+ def search(
39
+ query: str,
40
+ location: str | None,
41
+ category: str | None,
42
+ price_min: int | None,
43
+ price_max: int | None,
44
+ sort: str | None,
45
+ limit: int | None,
46
+ page: int,
47
+ output: str,
48
+ raw: bool,
49
+ ):
50
+ """Search listings on Blocket.
51
+
52
+ \b
53
+ Examples:
54
+ blocket search "soffa" -l stockholm --price-max 5000
55
+ blocket search "iphone 15" -c electronics --sort price-asc
56
+ blocket search "cykel" -c sports -o json
57
+ """
58
+ sort_map = {
59
+ "relevance": "RELEVANCE",
60
+ "price-asc": "PRICE_ASC",
61
+ "price-desc": "PRICE_DESC",
62
+ "date": "PUBLISHED_DESC",
63
+ }
64
+ try:
65
+ data = api.search(
66
+ query,
67
+ location=location,
68
+ category=category,
69
+ price_min=price_min,
70
+ price_max=price_max,
71
+ sort=sort_map.get(sort, sort) if sort else None,
72
+ page=page,
73
+ )
74
+ format.print_results(data, output=output, limit=limit, raw=raw)
75
+ except Exception as e:
76
+ click.echo(f"Error: {e}", err=True)
77
+ sys.exit(1)
78
+
79
+
80
+ @main.command()
81
+ @click.argument("ad_id")
82
+ @click.option("-o", "--output", type=click.Choice(["table", "json"]), default="table", help="Output format")
83
+ def ad(ad_id: str, output: str):
84
+ """Get full details for a specific ad.
85
+
86
+ \b
87
+ Examples:
88
+ blocket ad 20851738
89
+ blocket ad 20851738 -o json
90
+ """
91
+ try:
92
+ data = api.get_ad(ad_id)
93
+ format.print_ad(data, output=output)
94
+ except Exception as e:
95
+ click.echo(f"Error: {e}", err=True)
96
+ sys.exit(1)
97
+
98
+
99
+ @main.command()
100
+ def categories():
101
+ """List available categories."""
102
+ for name in sorted(api.CATEGORIES):
103
+ label = api.CATEGORY_LABELS.get(name, "")
104
+ click.echo(f"{name:<20} {label}")
105
+
106
+
107
+ @main.command()
108
+ def locations():
109
+ """List available locations (Swedish counties)."""
110
+ for name in sorted(api.LOCATIONS):
111
+ click.echo(name)
blocket_cli/format.py ADDED
@@ -0,0 +1,107 @@
1
+ """Output formatting for Blocket CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+ from datetime import datetime, timezone
8
+ from typing import Any
9
+
10
+
11
+ def _json_compact(data: Any) -> str:
12
+ return json.dumps(data, ensure_ascii=False, separators=(",", ":"))
13
+
14
+
15
+ def _slim(doc: dict) -> dict:
16
+ """Strip a listing to agent-essential fields."""
17
+ price = doc.get("price", {})
18
+ out: dict[str, Any] = {
19
+ "id": doc.get("id"),
20
+ "heading": doc.get("heading"),
21
+ "price": price.get("amount"),
22
+ "currency": price.get("currency_code", "SEK"),
23
+ "location": doc.get("location"),
24
+ "url": doc.get("canonical_url"),
25
+ }
26
+ ts = doc.get("timestamp")
27
+ if ts:
28
+ out["date"] = datetime.fromtimestamp(ts / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
29
+ for extra in doc.get("extras", []):
30
+ if extra.get("id") == "brand" and extra.get("values"):
31
+ out["brand"] = extra["values"][0]
32
+ return out
33
+
34
+
35
+ def print_results(data: dict, *, output: str = "table", limit: int | None = None, raw: bool = False) -> None:
36
+ """Print search results."""
37
+ docs = data.get("docs", [])
38
+ total = data.get("metadata", {}).get("result_size", {}).get("match_count", len(docs))
39
+
40
+ if limit:
41
+ docs = docs[:limit]
42
+
43
+ if output == "json":
44
+ results = docs if raw else [_slim(d) for d in docs]
45
+ print(_json_compact({"total": total, "results": results}))
46
+ return
47
+
48
+ if output == "jsonl":
49
+ for doc in docs:
50
+ print(_json_compact(doc if raw else _slim(doc)))
51
+ return
52
+
53
+ if not docs:
54
+ print("No results found.", file=sys.stderr)
55
+ return
56
+
57
+ print(f"Found {total:,} listings (showing {len(docs)}):\n")
58
+
59
+ for doc in docs:
60
+ price = doc.get("price", {})
61
+ amount = price.get("amount")
62
+ currency = price.get("price_unit", "kr")
63
+ location = doc.get("location", "")
64
+ heading = doc.get("heading", "Untitled")
65
+ url = doc.get("canonical_url", "")
66
+
67
+ price_str = f"{amount:,} {currency}".replace(",", " ") if amount else "—"
68
+
69
+ print(f" {heading}")
70
+ print(f" {price_str} · {location}")
71
+ print(f" {url}")
72
+ print()
73
+
74
+
75
+ def print_ad(data: dict, *, output: str = "table") -> None:
76
+ """Print ad details."""
77
+ if output == "json":
78
+ print(_json_compact(data))
79
+ return
80
+
81
+ if "error" in data:
82
+ print(f"Error: {data['error']}", file=sys.stderr)
83
+ return
84
+
85
+ title = data.get("name", data.get("title", "Untitled"))
86
+ desc = data.get("description", "")
87
+ offers = data.get("offers", {})
88
+ price = offers.get("price", "")
89
+ currency = offers.get("priceCurrency", "SEK")
90
+ condition = data.get("itemCondition", "").split("/")[-1] if data.get("itemCondition") else ""
91
+ brand = ""
92
+ if isinstance(data.get("brand"), dict):
93
+ brand = data["brand"].get("name", "")
94
+ url = data.get("url", "")
95
+
96
+ print(title)
97
+ print("=" * min(len(title), 60))
98
+ if brand:
99
+ print(f"Brand: {brand}")
100
+ if price:
101
+ print(f"Price: {price} {currency}")
102
+ if condition:
103
+ print(f"Condition: {condition}")
104
+ if desc:
105
+ print(f"\n{desc}")
106
+ if url:
107
+ print(f"\n{url}")
blocket_cli/py.typed ADDED
File without changes
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: blocket-cli
3
+ Version: 0.1.0
4
+ Summary: Fast CLI for searching Blocket.se — optimized for agents and scripting
5
+ Author: Lennart Johansson
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: blocket,cli,marketplace,search,sweden
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.10
16
+ Requires-Dist: click>=8.0
17
+ Requires-Dist: httpx>=0.27
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=8.0; extra == 'dev'
20
+ Requires-Dist: ruff>=0.9; extra == 'dev'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # blocket-cli
24
+
25
+ [![CI](https://github.com/lennart-johansson/blocket-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/lennart-johansson/blocket-cli/actions/workflows/ci.yml)
26
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://python.org)
27
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
28
+
29
+ Fast CLI for searching [Blocket.se](https://www.blocket.se) — Sweden's largest marketplace.
30
+
31
+ Designed for agents, scripts, and quick terminal lookups. Minimal dependencies, structured output.
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ pip install blocket-cli
37
+ ```
38
+
39
+ Or with [uv](https://docs.astral.sh/uv/):
40
+
41
+ ```bash
42
+ uv tool install blocket-cli
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ### Search listings
48
+
49
+ ```bash
50
+ blocket search "soffa"
51
+ blocket search "iphone 15" -l stockholm --price-max 8000
52
+ blocket search "mountainbike" -c sports --sort price-asc -n 10
53
+ blocket search "ps5" -c electronics -o json | jq '.results[:3]'
54
+ ```
55
+
56
+ ### Get ad details
57
+
58
+ ```bash
59
+ blocket ad 20851738
60
+ blocket ad 20851738 -o json
61
+ ```
62
+
63
+ ### Browse filters
64
+
65
+ ```bash
66
+ blocket categories
67
+ blocket locations
68
+ ```
69
+
70
+ ## Output formats
71
+
72
+ | Flag | Format | Use case |
73
+ |------|--------|----------|
74
+ | (default) | Human-readable table | Terminal browsing |
75
+ | `-o json` | Compact JSON | Piping to `jq`, API consumption |
76
+ | `-o jsonl` | One JSON object per line | Streaming, log processing |
77
+
78
+ ## Search options
79
+
80
+ | Option | Description |
81
+ |--------|-------------|
82
+ | `-l`, `--location` | Filter by Swedish county (e.g. `stockholm`, `skane`) |
83
+ | `-c`, `--category` | Filter by category (e.g. `electronics`, `furniture`) |
84
+ | `--price-min` | Minimum price in SEK |
85
+ | `--price-max` | Maximum price in SEK |
86
+ | `--sort` | Sort order (`relevance`, `price-asc`, `price-desc`, `date`) |
87
+ | `-n`, `--limit` | Max results to display |
88
+ | `-p`, `--page` | Page number |
89
+ | `-o`, `--output` | Output format (`table`, `json`, `jsonl`) |
90
+
91
+ ## Agent integration
92
+
93
+ The JSON output is designed for LLM agents and automation:
94
+
95
+ ```bash
96
+ # Structured search results
97
+ blocket search "cykel" -l stockholm --price-max 5000 -o json
98
+
99
+ # Stream results line by line
100
+ blocket search "soffa" -o jsonl
101
+
102
+ # Filter by category
103
+ blocket search "lampa" -c furniture -o json | jq '[.results[] | {title: .heading, price: .price.amount, location}]'
104
+ ```
105
+
106
+ ## License
107
+
108
+ MIT
@@ -0,0 +1,10 @@
1
+ blocket_cli/__init__.py,sha256=aXp7WGuX2Z4mgFsSMWnEIVAg2Yv50RmDVkDjX3Q-a3Q,103
2
+ blocket_cli/api.py,sha256=oshtvUz9FQ120_R4W2vkMaje5O6CtRAN6Tl7vxjHLqs,4580
3
+ blocket_cli/cli.py,sha256=1gLVQJPsxaFoZCNDoSAxshXxFZrmoyGryASzmhASQ2A,3177
4
+ blocket_cli/format.py,sha256=fMMBoEiAz1qCLDYJ63yUbQ6XKk2JYUNjN3CNylVhSMQ,3230
5
+ blocket_cli/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ blocket_cli-0.1.0.dist-info/METADATA,sha256=d3hCqfzAPt4xbEOwpf08HALzG_kCYyAkk8E5HDDjlmI,3008
7
+ blocket_cli-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
8
+ blocket_cli-0.1.0.dist-info/entry_points.txt,sha256=jeu7vIjf2bmgxDkZS2LE9fhJ2qu2qe6LrWd4oTKGBLU,49
9
+ blocket_cli-0.1.0.dist-info/licenses/LICENSE,sha256=iQbip7uvNVOsA4SxIhcb5UFELH10yh8vh4_lQqkfLFk,1074
10
+ blocket_cli-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ blocket = blocket_cli.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lennart Johansson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.