gmapsscraper-sdk 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,231 @@
1
+ """Official Python SDK for the gmapsscraper.io API.
2
+
3
+ Scrape Google Maps business data — names, addresses, phones, emails,
4
+ websites, ratings, reviews. Get a free API key (10 credits) at
5
+ https://gmapsscraper.io/dashboard
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import csv as _csv
11
+ import io
12
+ import json
13
+ import time
14
+ import urllib.error
15
+ import urllib.request
16
+ from urllib.parse import quote
17
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
18
+
19
+ __version__ = "0.1.0"
20
+ __all__ = ["GMapsScraper", "GMapsScraperError", "parse_csv"]
21
+
22
+ DEFAULT_BASE_URL = "https://gmapsscraper.io/api/v1"
23
+
24
+ # (method, url, headers, body) -> (status_code, response_text)
25
+ HttpCallable = Callable[[str, str, Dict[str, str], Optional[str]], Tuple[int, str]]
26
+
27
+ BusinessRecord = Dict[str, str]
28
+ Job = Dict[str, Any]
29
+
30
+
31
+ class GMapsScraperError(Exception):
32
+ """Raised for HTTP errors, network failures, failed jobs and timeouts.
33
+
34
+ Attributes:
35
+ status: HTTP status code, if the error came from an HTTP response.
36
+ body: Parsed JSON error body or failed job dict, when available.
37
+ """
38
+
39
+ def __init__(self, message: str, status: Optional[int] = None, body: Any = None):
40
+ super().__init__(message)
41
+ self.status = status
42
+ self.body = body
43
+
44
+
45
+ def _default_http(
46
+ method: str, url: str, headers: Dict[str, str], body: Optional[str], timeout: float = 120.0
47
+ ) -> Tuple[int, str]:
48
+ request = urllib.request.Request(
49
+ url,
50
+ data=body.encode("utf-8") if body is not None else None,
51
+ headers=headers,
52
+ method=method,
53
+ )
54
+ try:
55
+ with urllib.request.urlopen(request, timeout=timeout) as response:
56
+ return response.getcode(), response.read().decode("utf-8")
57
+ except urllib.error.HTTPError as exc:
58
+ return exc.code, exc.read().decode("utf-8", "replace")
59
+
60
+
61
+ class GMapsScraper:
62
+ """Client for the gmapsscraper.io REST API.
63
+
64
+ Args:
65
+ api_key: Your API key — get one at https://gmapsscraper.io/dashboard
66
+ base_url: API base URL (default: https://gmapsscraper.io/api/v1).
67
+ http_timeout: Per-request HTTP timeout in seconds for the default
68
+ transport (default: 120). Independent of the job-polling ``timeout``.
69
+ http: Optional transport override for testing:
70
+ ``(method, url, headers, body) -> (status_code, response_text)``.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ api_key: str,
76
+ *,
77
+ base_url: str = DEFAULT_BASE_URL,
78
+ http_timeout: float = 120.0,
79
+ http: Optional[HttpCallable] = None,
80
+ ):
81
+ if not isinstance(api_key, str) or not api_key.strip():
82
+ raise TypeError("api_key is required — get one at https://gmapsscraper.io/dashboard")
83
+ self._api_key = api_key
84
+ self.base_url = base_url.rstrip("/")
85
+ self._http = http or (
86
+ lambda method, url, headers, body: _default_http(method, url, headers, body, timeout=http_timeout)
87
+ )
88
+
89
+ def __repr__(self) -> str: # never expose the API key in logs/repr
90
+ return f"GMapsScraper(base_url={self.base_url!r})"
91
+
92
+ def _request(self, path: str, *, method: str = "GET", body: Any = None, raw: bool = False) -> Any:
93
+ headers = {
94
+ "Authorization": f"Bearer {self._api_key}",
95
+ "User-Agent": f"gmapsscraper-python/{__version__}",
96
+ }
97
+ payload = None
98
+ if body is not None:
99
+ headers["Content-Type"] = "application/json"
100
+ payload = json.dumps(body)
101
+ try:
102
+ status, text = self._http(method, f"{self.base_url}{path}", headers, payload)
103
+ except GMapsScraperError:
104
+ raise
105
+ except Exception as exc:
106
+ raise GMapsScraperError(f"Network error: {exc}") from exc
107
+ if not 200 <= status < 300:
108
+ err_body: Any = None
109
+ try:
110
+ err_body = json.loads(text)
111
+ except ValueError:
112
+ pass
113
+ api_error = err_body.get("error") if isinstance(err_body, dict) else None
114
+ if isinstance(api_error, str) and api_error:
115
+ message = api_error
116
+ elif api_error is not None:
117
+ message = json.dumps(api_error)
118
+ else:
119
+ message = f"Request failed with HTTP {status}"
120
+ raise GMapsScraperError(message, status=status, body=err_body)
121
+ if raw:
122
+ return text
123
+ try:
124
+ return json.loads(text)
125
+ except ValueError as exc:
126
+ raise GMapsScraperError(f"Failed to parse response: {exc}", status=status) from exc
127
+
128
+ def create_job(self, keywords: Union[str, Iterable[str]], **options: Any) -> Dict[str, Any]:
129
+ """Submit a scrape job. Costs 2 credits.
130
+
131
+ Option names match the REST API wire format and are stable:
132
+ ``email``, ``depth``, ``zoom``, ``radius``, ``lang``, ``fast_mode``,
133
+ ``max_time``, ``lat``, ``lon``, ``name``.
134
+
135
+ Returns:
136
+ ``{"id": "job_xxx", "credits_remaining": 8}``
137
+ """
138
+ try:
139
+ kw = [keywords] if isinstance(keywords, str) else list(keywords)
140
+ except TypeError:
141
+ raise TypeError(
142
+ 'keywords must be a non-empty string or an iterable of non-empty strings, '
143
+ 'e.g. "coffee shop in Austin TX"'
144
+ ) from None
145
+ if not kw or any(not isinstance(k, str) or not k.strip() for k in kw):
146
+ raise TypeError(
147
+ 'keywords must be a non-empty string or an iterable of non-empty strings, '
148
+ 'e.g. "coffee shop in Austin TX"'
149
+ )
150
+ return self._request("/scrape", method="POST", body={**options, "keywords": kw})
151
+
152
+ def get_job(self, job_id: str) -> Job:
153
+ """Get job status: ``{"id", "status": "running"|"complete"|"failed", "name"}``."""
154
+ return self._request(f"/jobs/{quote(job_id, safe='')}")
155
+
156
+ def wait_for_job(
157
+ self,
158
+ job_id: str,
159
+ *,
160
+ poll_interval: float = 10.0,
161
+ timeout: float = 3600.0,
162
+ on_progress: Optional[Callable[[Job], None]] = None,
163
+ ) -> Job:
164
+ """Poll a job until it completes; raises GMapsScraperError on failure or timeout."""
165
+ start = time.monotonic()
166
+ while True:
167
+ job = self.get_job(job_id)
168
+ if on_progress is not None:
169
+ on_progress(job)
170
+ status = job.get("status")
171
+ if status == "complete":
172
+ return job
173
+ if status == "failed":
174
+ reason = job.get("error")
175
+ suffix = f": {reason}" if isinstance(reason, str) and reason else ""
176
+ raise GMapsScraperError(f"Job {job_id} failed{suffix}", body=job)
177
+ remaining = timeout - (time.monotonic() - start)
178
+ if remaining <= 0:
179
+ raise GMapsScraperError(f"Timed out after {timeout}s waiting for job {job_id}", body=job)
180
+ time.sleep(min(poll_interval, remaining))
181
+
182
+ def download_csv(self, job_id: str) -> str:
183
+ """Download job results as a raw CSV string.
184
+
185
+ Columns: title, address, phone, email, website, rating, reviews_count,
186
+ category, latitude, longitude, google_maps_url, opening_hours.
187
+
188
+ Note: the full CSV is buffered in memory; typical result sets are a few
189
+ hundred KB at most.
190
+ """
191
+ return self._request(f"/jobs/{quote(job_id, safe='')}/download", raw=True)
192
+
193
+ def download_records(self, job_id: str) -> List[BusinessRecord]:
194
+ """Download job results parsed into a list of dicts (one per business)."""
195
+ return parse_csv(self.download_csv(job_id))
196
+
197
+ def scrape(
198
+ self,
199
+ keywords: Union[str, Iterable[str]],
200
+ *,
201
+ poll_interval: float = 10.0,
202
+ timeout: float = 3600.0,
203
+ on_progress: Optional[Callable[[Job], None]] = None,
204
+ **options: Any,
205
+ ) -> List[BusinessRecord]:
206
+ """One call: create a job, wait for completion, return parsed records."""
207
+ job = self.create_job(keywords, **options)
208
+ job_id = job.get("id") if isinstance(job, dict) else None
209
+ if not job_id:
210
+ raise GMapsScraperError("Malformed response from /scrape: missing job id", body=job)
211
+ self.wait_for_job(job_id, poll_interval=poll_interval, timeout=timeout, on_progress=on_progress)
212
+ return self.download_records(job_id)
213
+
214
+ def credits(self) -> Dict[str, Any]:
215
+ """Get remaining credit balance: ``{"credits": 8}``."""
216
+ return self._request("/credits")
217
+
218
+
219
+ def parse_csv(text: str) -> List[BusinessRecord]:
220
+ """Parse RFC 4180 CSV text (strips a UTF-8 BOM) into a list of dicts."""
221
+ if text.startswith("\ufeff"):
222
+ text = text[1:]
223
+ reader = _csv.DictReader(io.StringIO(text))
224
+ records: List[BusinessRecord] = []
225
+ for row in reader:
226
+ records.append({
227
+ key: (value if isinstance(value, str) else "")
228
+ for key, value in row.items()
229
+ if key is not None
230
+ })
231
+ return records
gmapsscraper/py.typed ADDED
File without changes
@@ -0,0 +1,159 @@
1
+ Metadata-Version: 2.4
2
+ Name: gmapsscraper-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the gmapsscraper.io API — scrape Google Maps business data: names, emails, phones, websites, ratings, reviews.
5
+ Project-URL: Homepage, https://gmapsscraper.io
6
+ Project-URL: Repository, https://github.com/gmapsscraper/gmapsscraper-python
7
+ Project-URL: Documentation, https://gmapsscraper.io/llms.txt
8
+ Project-URL: Issues, https://github.com/gmapsscraper/gmapsscraper-python/issues
9
+ Author: gmapsscraper.io
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: api client,b2b,business data,email extractor,google maps,google maps scraper,lead generation,leads,local business,places,reviews,scraper,sdk
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Internet :: WWW/HTTP
24
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.9
27
+ Description-Content-Type: text/markdown
28
+
29
+ # gmapsscraper
30
+
31
+ [![PyPI version](https://img.shields.io/pypi/v/gmapsscraper-sdk.svg)](https://pypi.org/project/gmapsscraper-sdk/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/gmapsscraper-sdk.svg)](https://pypi.org/project/gmapsscraper-sdk/)
33
+ [![license](https://img.shields.io/pypi/l/gmapsscraper-sdk.svg)](./LICENSE)
34
+
35
+ Official Python SDK for the [gmapsscraper.io](https://gmapsscraper.io) API — a **Google Maps scraper** for lead generation. Extract business names, addresses, phone numbers, **emails**, websites, ratings, review counts, categories and coordinates from Google Maps in a few lines of Python.
36
+
37
+ - 🪶 **Zero dependencies** — pure standard library (`urllib` + `csv`)
38
+ - 🐍 **Python 3.9+**, fully type-hinted (`py.typed`)
39
+ - 📧 **Email extraction** — crawls business websites for contact emails
40
+ - 🗺️ **Auto-geocoding** — just write `"dentist in Chicago IL"`, no coordinates needed
41
+
42
+ ## Install
43
+
44
+ ```bash
45
+ pip install gmapsscraper-sdk
46
+ ```
47
+
48
+ The import name is simply `gmapsscraper`:
49
+
50
+ Get a free API key (10 credits = 5 searches, no credit card) at **[gmapsscraper.io/dashboard](https://gmapsscraper.io/dashboard)**.
51
+
52
+ ## Quick start
53
+
54
+ ```python
55
+ from gmapsscraper import GMapsScraper
56
+
57
+ client = GMapsScraper("YOUR_API_KEY")
58
+
59
+ # One call: submit → poll → download parsed results
60
+ leads = client.scrape("coffee shop in Austin TX", email=True)
61
+
62
+ print(len(leads), "businesses found")
63
+ print(leads[0])
64
+ # {
65
+ # "title": "Houndstooth Coffee",
66
+ # "address": "401 Congress Ave ...",
67
+ # "phone": "+1 512-...",
68
+ # "email": "hello@...",
69
+ # "website": "https://...",
70
+ # "rating": "4.7",
71
+ # "reviews_count": "1912",
72
+ # "category": "Coffee shop",
73
+ # "latitude": "30.2672", "longitude": "-97.7431",
74
+ # "google_maps_url": "https://www.google.com/maps/place/...",
75
+ # "opening_hours": "..."
76
+ # }
77
+ ```
78
+
79
+ ## Step-by-step API
80
+
81
+ If you want control over each stage (e.g. queue jobs and collect later):
82
+
83
+ ```python
84
+ # 1. Submit a job (costs 2 credits, multiple keywords = same cost)
85
+ job = client.create_job(
86
+ ["plumber in Miami FL", "plumbing service in Miami FL"],
87
+ email=True, depth=2,
88
+ )
89
+
90
+ # 2. Wait for completion (polls every 10s)
91
+ client.wait_for_job(job["id"], on_progress=lambda j: print("status:", j["status"]))
92
+
93
+ # 3a. Parsed dicts…
94
+ records = client.download_records(job["id"])
95
+
96
+ # 3b. …or the raw CSV
97
+ csv_text = client.download_csv(job["id"])
98
+
99
+ # Check your balance
100
+ balance = client.credits() # {"credits": 8}
101
+ ```
102
+
103
+ ## Options
104
+
105
+ All options for `scrape()` / `create_job()` (names match the REST API wire format and are stable):
106
+
107
+ | Option | Type | Default | Description |
108
+ | ----------- | -------------- | ------- | ---------------------------------------------------- |
109
+ | `email` | bool | `False` | Extract business emails from websites |
110
+ | `depth` | int (1–2) | `2` | Higher = more results, **same credit cost** |
111
+ | `zoom` | int (1–21) | `15` | Map zoom level |
112
+ | `radius` | int (meters) | `20000` | Search radius |
113
+ | `lang` | str | `"en"` | ISO 639-1 result language |
114
+ | `fast_mode` | bool | `True` | Skip deep website crawling |
115
+ | `max_time` | int (s) | `3600` | Job timeout on the backend |
116
+ | `lat`/`lon` | str \| float | — | Coordinates (auto-geocoded from keywords if omitted) |
117
+
118
+ `scrape()` and `wait_for_job()` also accept `poll_interval` (seconds, default `10` — the API minimum; keep it there to avoid rate limits), `timeout` (seconds, default `3600`) and `on_progress(job)`.
119
+
120
+ ## Error handling
121
+
122
+ All failures — HTTP errors, network failures, failed jobs and timeouts — raise `GMapsScraperError` with `status` and `body`. Invalid arguments raise `TypeError`:
123
+
124
+ ```python
125
+ from gmapsscraper import GMapsScraper, GMapsScraperError
126
+
127
+ try:
128
+ client.scrape("dentist in Chicago IL")
129
+ except GMapsScraperError as err:
130
+ # 401 invalid key · 402 out of credits · 422 bad params · 429 rate limited
131
+ print(err.status, err)
132
+ ```
133
+
134
+ | Status | Meaning |
135
+ | ------ | -------------------------------------------------------------------------- |
136
+ | 401 | Invalid API key |
137
+ | 402 | Insufficient credits — top up at [gmapsscraper.io](https://gmapsscraper.io/#pricing) |
138
+ | 422 | Invalid parameters |
139
+ | 429 | Rate limited (1000 req/day) or too many concurrent jobs (max 10) |
140
+ | 502 | Backend temporarily unavailable |
141
+
142
+ ## Tips for better results
143
+
144
+ - Be specific: `"vegan restaurant in Brooklyn NY"` beats `"restaurant in New York"`.
145
+ - Pass several related keywords in one job — broader coverage, same 2 credits.
146
+ - Set `email=True` whenever you need contact info for cold outreach.
147
+ - Jobs typically finish in 30–120 seconds.
148
+
149
+ ## Related resources
150
+
151
+ - 📘 [API documentation](https://gmapsscraper.io/llms.txt) (also great as LLM context)
152
+ - 📦 [Node.js SDK](https://github.com/gmapsscraper/gmapsscraper-js) — `npm install @gmapsscraper/sdk`
153
+ - 🤖 [Claude / AI agent skills](https://github.com/gmapsscraper/google-maps-agent-skills) — use gmapsscraper from Claude Code and other agents
154
+ - 🧩 [Chrome extension](https://github.com/gmapsscraper/google-maps-scraper) — scrape Google Maps without code
155
+ - ✍️ [Blog: Google Maps scraping guides](https://gmapsscraper.io/blog)
156
+
157
+ ## License
158
+
159
+ [MIT](./LICENSE) © [gmapsscraper.io](https://gmapsscraper.io)
@@ -0,0 +1,6 @@
1
+ gmapsscraper/__init__.py,sha256=OYja3l3XOLdWh_AcXUZti7F_MooY-I1o3V9xi4hNwcU,8973
2
+ gmapsscraper/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ gmapsscraper_sdk-0.1.0.dist-info/METADATA,sha256=nEaNoVqQccr49MUOpRgddW6nT0z9_mpbFvRBjJVW3Z8,7143
4
+ gmapsscraper_sdk-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
5
+ gmapsscraper_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=fCgj4saUI4ByHZbHiIm1v84ojd_gifiCfrTX3I1ZG-A,1072
6
+ gmapsscraper_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.31.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gmapsscraper.io
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.