@mrscraper/sdk 1.1.3 → 2.0.0

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.
package/README.md CHANGED
@@ -1,426 +1,130 @@
1
1
  # @mrscraper/sdk
2
- ![](./mrscraper.jpeg)
3
-
4
- Official Node.js SDK for the [MrScraper](https://mrscraper.com) API.
5
-
6
- Scrape any data from any websites.
7
- Unblock pages, create and scale AI scrapers, manual scrapers, and retrieve results synchronously and asynchronously.
8
- It is stealth, reliable, and scalable.
9
- Every action is mirrored on our platform https://app.mrscraper.com
10
-
11
- [![npm version](https://img.shields.io/npm/v/@mrscraper/sdk)](https://www.npmjs.com/package/@mrscraper/sdk)
12
- [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](./LICENSE)
13
2
 
14
- ## Table of Contents
15
-
16
- - [Installation](#installation)
17
- - [Requirements](#requirements)
18
- - [Authentication](#authentication)
19
- - [Quick Start](#quick-start)
20
- - [Error Handling](#error-handling)
21
- - [API Reference](#api-reference)
22
- - [fetchHtml](#fetchhtml)
23
- - [createAiScraper](#createaiscraper)
24
- - [rerunAiScraper](#rerunaiscraper)
25
- - [bulkRerunAiScraper](#bulkrerunaiscraper)
26
- - [rerunManualScraper](#rerunmanualscraper)
27
- - [bulkRerunManualScraper](#bulkrerunmanualscraper)
28
- - [getAllResults](#getallresults)
29
- - [getResultById](#getresultbyid)
30
- - [googleSerp](#googleserp)
31
- - [Trying the SDK locally](#trying-the-sdk-locally)
32
- - [TypeScript](#typescript)
33
- - [License](#license)
3
+ ![](./mrscraper.jpeg)
34
4
 
35
- ---
5
+ Node.js SDK for [MrScraper](https://mrscraper.com) content fetching and Google search results. Requires Node.js 18 or newer and ES modules.
36
6
 
37
- ## Installation
7
+ ## Install and authenticate
38
8
 
39
9
  ```bash
40
10
  npm install @mrscraper/sdk
11
+ export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
41
12
  ```
42
13
 
43
- ## Requirements
44
-
45
- - Node.js >= 18
46
- - Your project must use ES Modules. Add `"type": "module"` to your `package.json`:
47
-
48
- ## Authentication
49
-
50
- Get your API token from your [MrScraper dashboard](https://app.mrscraper.com) and set it as an environment variable:
51
-
52
- ```bash
53
- export MRSCRAPER_API_TOKEN=your_token_here
54
- ```
55
-
56
- Every function also accepts an optional `token` parameter to override the environment variable on a per-call basis.
57
-
58
- ---
59
-
60
- ## Quick Start
61
-
62
- ```typescript
63
- import { fetchHtml, createAiScraper, getResultById, MrScraperError } from "@mrscraper/sdk";
64
-
65
- try {
66
- // 1. Fetch raw HTML of a page
67
- const html = await fetchHtml({ url: "https://example.com" });
68
- console.log(html);
69
-
70
- // 2. Create an AI scraper and get its result
71
- const scraper = await createAiScraper({
72
- url: "https://example.com/products",
73
- message: "Extract all product names and prices",
74
- agent: "listing",
75
- });
76
- console.log(scraper);
77
- } catch (err) {
78
- if (err instanceof MrScraperError) {
79
- console.error(`[${err.status ?? "network"}] ${err.message}`);
80
- } else {
81
- throw err;
82
- }
83
- }
84
- ```
85
-
86
- ---
14
+ The SDK reads `MRSCRAPER_API_TOKEN` automatically. You can instead pass `token` in either call's options object. Both functions are async and return `{ status_code, data, headers }`. JSON responses are parsed; other responses are returned as text in `data`.
87
15
 
88
- ## Error Handling
16
+ **Version 2 migration:** This release removes `fetchHtml`, `googleSerp`, and all AI scraper, manual scraper, and results methods. Use `fetch_content(url, options)` and `google_serp(queryOrUrl, options)`. Both functions now return a response wrapper instead of only the API payload.
89
17
 
90
- All functions throw a `MrScraperError` on failure — whether the error comes from the API (4xx/5xx), a network issue, or a timeout. You never need to check a return value; just wrap calls in `try/catch`.
18
+ ## Fetch content
91
19
 
92
20
  ```typescript
93
- import { MrScraperError } from "@mrscraper/sdk";
94
-
95
- try {
96
- const html = await fetchHtml({ url: "https://example.com" });
97
- } catch (err) {
98
- if (err instanceof MrScraperError) {
99
- console.error(err.message); // Human-readable error message
100
- console.error(err.status); // HTTP status code, or undefined for network errors
101
- }
102
- }
103
- ```
21
+ import { fetch_content } from "@mrscraper/sdk";
104
22
 
105
- **`MrScraperError` properties:**
106
-
107
- | Property | Type | Description |
108
- |----------|------|-------------|
109
- | `message` | `string` | Human-readable description of the error |
110
- | `status` | `number \| undefined` | HTTP status code (e.g. `401`, `429`, `500`). `undefined` for network/timeout errors |
111
- | `name` | `string` | Always `"MrScraperError"` |
112
-
113
- ---
114
-
115
- ## API Reference
116
-
117
- ### `fetchHtml`
118
-
119
- Fetches the raw HTML (or JSON) of any URL through MrScraper's Fetch endpoint.
120
-
121
- ```typescript
122
- const html = await fetchHtml({
123
- url: "https://example.com", // required
124
- timeout: 120, // optional – seconds (1–600), default: 120
125
- geoCode: "US", // optional – 2-letter country code, default: "US"
126
- blockResources: false, // optional – block images/CSS/fonts, default: false
127
- token: "your_token", // optional – overrides MRSCRAPER_API_TOKEN
23
+ const result = await fetch_content("https://example.com", {
24
+ html: true,
25
+ markdown: true,
26
+ screenshot: true,
27
+ super: true,
128
28
  });
29
+ console.log(result.status_code, result.data);
129
30
  ```
130
31
 
131
- **Options:**
132
-
133
- | Parameter | Type | Required | Default | Description |
134
- |-----------|------|----------|---------|-------------|
135
- | `url` | `string` | Yes | — | The URL to fetch |
136
- | `timeout` | `number` | No | `120` | Request timeout in seconds (1–600) |
137
- | `geoCode` | `string` | No | `"US"` | Two-letter ISO country code for geo-targeting |
138
- | `blockResources` | `boolean` | No | `false` | Block images, fonts, and CSS to speed up the request |
139
- | `token` | `string` | No | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
140
-
141
- **Returns:** `Promise<string>` — the raw HTML (or JSON string) of the page.
142
-
143
- ---
144
-
145
- ### `createAiScraper`
146
-
147
- Creates a new AI scraper. Supports three agent types:
148
-
149
- - **`general`** — extracts structured data based on your natural-language `message`
150
- - **`listing`** — optimised for list/collection pages (products, jobs, articles, etc.)
151
- - **`map`** — crawls a site to discover and map all URLs
32
+ `fetch_content` sends `POST https://api.mrscraper.com/`. The JSON body contains `url`, `maxRetries`, and optional `tokenCap`. Page settings and the token are URL query parameters. Setting `screenshot: true` also sends `browserRendering=true`, even if `browser_rendering` is false.
33
+
34
+ | Option | Default | Description |
35
+ |--------|---------|-------------|
36
+ | `url` | Required first argument | Page URL |
37
+ | `token` | Environment variable | API token override |
38
+ | `html`, `markdown` | `true`, `false` | Request HTML, Markdown, or both |
39
+ | `timeout` | `120` | Page timeout in seconds, from 1 to 300; HTTP timeout is 30 seconds longer |
40
+ | `geo_code`, `proxy_country` | `"US"`, unset | Geolocation and optional proxy country |
41
+ | `browser_rendering` | unset | `true` to force a browser, `false` to disable it, unset for automatic fallback |
42
+ | `screenshot` | `false` | Capture a screenshot and force browser rendering |
43
+ | `super` | `false` | Enable real device routing |
44
+ | `use_proxy`, `proxy` | `true`, unset | Allow a proxy or supply `username:password@host:port` |
45
+ | `home_page` | `false` | Visit the site's root first; sends `warmStart=true` |
46
+ | `wait_for_selector` | unset | Wait for a CSS selector |
47
+ | `block_resources`, `bypass_proxy` | `false`, `false` | Block resources or enable proxy bypass behavior |
48
+ | `cookie_jar`, `headers` | unset | Cookie configuration and target request headers; `headers` accepts an object or JSON string |
49
+ | `max_retries`, `token_cap` | `3`, unset | Retry count and optional token budget |
50
+ | `stream` | unset | Request a streamed response, buffered into the normal return value |
51
+ | `discard_token_secret` | `""` | Value for the `x-discard-token-secret` API header |
52
+
53
+ Unset optional query parameters are omitted. Explicit `false`, `0`, and empty strings are preserved where the Python client sends them.
54
+
55
+ ## Google SERP
152
56
 
153
57
  ```typescript
154
- // General / listing agent
155
- const scraper = await createAiScraper({
156
- url: "https://example.com/products",
157
- message: "Extract all product names and prices",
158
- agent: "listing", // "general" | "listing" | "map", default: "general"
159
- proxyCountry: "US", // optional
160
- });
161
-
162
- // Map agent
163
- const scraper = await createAiScraper({
164
- url: "https://example.com",
165
- agent: "map",
166
- maxDepth: 2, // optional – default: 2
167
- maxPages: 50, // optional – default: 50
168
- limit: 1000, // optional – default: 1000
169
- includePatterns: "/blog", // optional
170
- excludePatterns: "/admin", // optional
58
+ import { google_serp } from "@mrscraper/sdk";
59
+
60
+ const result = await google_serp("python web scraping", {
61
+ raw: false,
62
+ region: "us",
63
+ language: "en",
64
+ page: 1,
65
+ format: "json",
171
66
  });
67
+ console.log(result.data);
172
68
  ```
173
69
 
174
- **Options:**
70
+ `google_serp` sends `POST https://sync.scraper.mrscraper.com/api/google/serp/v2/sync`. The first argument may be query text or a Google search URL. For a URL, the SDK extracts `q`, `gl`, `hl`, and `start`; explicit options override the extracted region, language, and page. `raw: true` is the default and requests HTML regardless of `format`. Set `raw: false` to use `format`.
175
71
 
176
- | Parameter | Type | Required | Default | Description |
177
- |-----------|------|----------|---------|-------------|
178
- | `url` | `string` | Yes | — | Starting URL to scrape |
179
- | `message` | `string` | No | `""` | Natural-language instructions (general/listing agents) |
180
- | `agent` | `"general" \| "listing" \| "map"` | No | `"general"` | Agent type |
181
- | `proxyCountry` | `string \| null` | No | — | Two-letter proxy country code (general/listing) |
182
- | `maxDepth` | `number` | No | `2` | Max crawl depth, 0–5 (map agent) |
183
- | `maxPages` | `number` | No | `50` | Max pages to crawl, 1–1000 (map agent) |
184
- | `limit` | `number` | No | `1000` | Max results to return, 1–100000 (map agent) |
185
- | `includePatterns` | `string` | No | `""` | URL patterns to include (map agent) |
186
- | `excludePatterns` | `string` | No | `""` | URL patterns to exclude (map agent) |
187
- | `token` | `string` | No | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
72
+ | Option | Default | Description |
73
+ |--------|---------|-------------|
74
+ | `url` | Required first argument | Search query or Google search URL |
75
+ | `token` | Environment variable | API token override |
76
+ | `raw` | `true` | Request HTML when true |
77
+ | `format` | `"json"` | `"json"` or `"html"` when `raw` is false |
78
+ | `region`, `language` | unset | Country and language |
79
+ | `page` | unset | One based result page |
80
+ | `render_js` | `false` | Render JavaScript features |
81
+ | `timeout` | `600` | HTTP request timeout in seconds |
188
82
 
189
- **Returns:** `Promise<unknown>` — the API response object.
83
+ ## Errors and types
190
84
 
191
- ---
192
-
193
- ### `rerunAiScraper`
194
-
195
- Reruns an existing AI scraper on a new URL.
196
-
197
- ```typescript
198
- const result = await rerunAiScraper({
199
- scraperId: "your-scraper-id", // required
200
- url: "https://example.com/new-page", // required
201
- maxDepth: 2, // optional
202
- maxPages: 50, // optional
203
- limit: 1000, // optional
204
- includePatterns: "", // optional
205
- excludePatterns: "", // optional
206
- });
207
- ```
208
-
209
- **Options:**
210
-
211
- | Parameter | Type | Required | Default | Description |
212
- |-----------|------|----------|---------|-------------|
213
- | `scraperId` | `string` | Yes | — | ID of the AI scraper to rerun |
214
- | `url` | `string` | Yes | — | New URL to scrape |
215
- | `maxDepth` | `number` | No | `2` | Max crawl depth (0–5) |
216
- | `maxPages` | `number` | No | `50` | Max pages (1–1000) |
217
- | `limit` | `number` | No | `1000` | Max results (1–100000) |
218
- | `includePatterns` | `string` | No | `""` | URL patterns to include |
219
- | `excludePatterns` | `string` | No | `""` | URL patterns to exclude |
220
- | `token` | `string` | No | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
221
-
222
- **Returns:** `Promise<unknown>` — the API response object.
223
-
224
- ---
225
-
226
- ### `bulkRerunAiScraper`
227
-
228
- Reruns an AI scraper on multiple URLs at once.
85
+ Both functions reject with `MrScraperError` for API, authentication, network, and timeout errors. `status` contains the HTTP status for API errors and is `undefined` for network errors. Invalid options throw `TypeError` or `RangeError`.
229
86
 
230
87
  ```typescript
231
- const result = await bulkRerunAiScraper({
232
- scraperId: "your-scraper-id",
233
- urls: [
234
- "https://example.com/page1",
235
- "https://example.com/page2",
236
- ],
237
- });
238
- ```
88
+ import { fetch_content, MrScraperError } from "@mrscraper/sdk";
89
+ import type { FetchContentOptions, GoogleSerpOptions, MrScraperResponse } from "@mrscraper/sdk";
239
90
 
240
- **Options:**
241
-
242
- | Parameter | Type | Required | Description |
243
- |-----------|------|----------|-------------|
244
- | `scraperId` | `string` | Yes | ID of the AI scraper to rerun |
245
- | `urls` | `string[]` | Yes | List of URLs to scrape |
246
- | `token` | `string` | No | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
247
-
248
- **Returns:** `Promise<unknown>` — the API response object.
249
-
250
- ---
251
-
252
- ### `rerunManualScraper`
253
- Reruns a manual (dashboard-configured) scraper on a URL.
254
-
255
- ```typescript
256
- const result = await rerunManualScraper({
257
- scraperId: "your-scraper-id",
258
- url: "https://example.com/target",
259
- });
260
- ```
261
-
262
- **Options:**
263
-
264
- | Parameter | Type | Required | Description |
265
- |-----------|------|----------|-------------|
266
- | `scraperId` | `string` | Yes | ID of the manual scraper to rerun |
267
- | `url` | `string` | Yes | URL to scrape |
268
- | `token` | `string` | No | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
269
-
270
- **Returns:** `Promise<unknown>` — the API response object.
271
-
272
- ---
273
-
274
- ### `bulkRerunManualScraper`
275
-
276
- Reruns a manual scraper on multiple URLs at once.
277
-
278
- ```typescript
279
- const result = await bulkRerunManualScraper({
280
- scraperId: "your-scraper-id",
281
- urls: [
282
- "https://example.com/a",
283
- "https://example.com/b",
284
- ],
285
- });
286
- ```
287
-
288
- **Options:**
289
-
290
- | Parameter | Type | Required | Description |
291
- |-----------|------|----------|-------------|
292
- | `scraperId` | `string` | Yes | ID of the manual scraper to rerun |
293
- | `urls` | `string[]` | Yes | List of URLs to scrape |
294
- | `token` | `string` | No | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
295
-
296
- **Returns:** `Promise<unknown>` — the API response object.
297
-
298
- ---
299
-
300
- ### `getAllResults`
301
-
302
- Lists scraping results with sorting, pagination, search, and date range filters. All options are optional.
303
-
304
- ```typescript
305
- const results = await getAllResults({
306
- sortField: "updatedAt", // default
307
- sortOrder: "DESC", // default
308
- pageSize: 10, // default
309
- page: 1, // default
310
- search: "example.com", // optional
311
- dateRangeColumn: "createdAt", // optional
312
- startAt: "2024-01-01T00:00:00Z", // optional – ISO 8601
313
- endAt: "2024-12-31T23:59:59Z", // optional – ISO 8601
314
- });
91
+ try {
92
+ const result: MrScraperResponse = await fetch_content("https://example.com");
93
+ console.log(result.data);
94
+ } catch (error) {
95
+ if (error instanceof MrScraperError) {
96
+ console.error(error.status, error.message);
97
+ } else {
98
+ throw error;
99
+ }
100
+ }
315
101
  ```
316
102
 
317
- **Options:**
318
-
319
- | Parameter | Type | Default | Description |
320
- |-----------|------|---------|-------------|
321
- | `sortField` | `SortField` | `"updatedAt"` | Field to sort by |
322
- | `sortOrder` | `"ASC" \| "DESC"` | `"DESC"` | Sort direction |
323
- | `pageSize` | `number` | `10` | Results per page (1–500) |
324
- | `page` | `number` | `1` | Page number (1-based) |
325
- | `search` | `string` | — | Full-text search query |
326
- | `dateRangeColumn` | `string` | — | Column to filter by date range |
327
- | `startAt` | `string` | — | Start of date range (ISO 8601) |
328
- | `endAt` | `string` | — | End of date range (ISO 8601) |
329
- | `token` | `string` | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
330
-
331
- **`SortField` values:** `"createdAt"` `"updatedAt"` `"id"` `"type"` `"url"` `"status"` `"error"` `"tokenUsage"` `"runtime"`
332
-
333
- **Returns:** `Promise<unknown>` — paginated list of results.
334
-
335
- ---
336
-
337
- ### `getResultById`
338
-
339
- Fetches a single scraping result by its ID.
103
+ ## Develop
340
104
 
341
- ```typescript
342
- const result = await getResultById({ resultId: "your-result-id" });
343
- console.log(result);
105
+ ```bash
106
+ npm ci
107
+ npm test
108
+ npm run build
344
109
  ```
345
110
 
346
- **Options:**
347
-
348
- | Parameter | Type | Required | Description |
349
- |-----------|------|----------|-------------|
350
- | `resultId` | `string` | Yes | ID of the result to fetch |
351
- | `token` | `string` | No | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
352
-
353
- **Returns:** `Promise<unknown>` — the result object.
111
+ `npm test` uses mocked HTTP responses and does not require an API token.
354
112
 
355
- ---
113
+ To make live requests with both SDK functions, set your token and run the manual script:
356
114
 
357
- ### `googleSerp`
358
-
359
- Calls the synchronous Google SERP endpoint on the sync scraper API. Authenticates with a **Bearer** token (same token as `MRSCRAPER_API_TOKEN`).
360
-
361
- ```typescript
362
- import { googleSerp } from "@mrscraper/sdk";
363
-
364
- const data = await googleSerp({
365
- url: "https://www.google.com/search?q=iphone+17", // required – full Google SERP URL
366
- raw: true, // optional – default: false
367
- timeoutMs: 300_000, // optional – ms, default: 300000 (5 min)
368
- token: "your_token", // optional – overrides MRSCRAPER_API_TOKEN
369
- });
115
+ ```bash
116
+ export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
117
+ npm run test:manual
370
118
  ```
371
119
 
372
- **Options:**
373
-
374
- | Parameter | Type | Required | Default | Description |
375
- |-----------|------|----------|---------|-------------|
376
- | `url` | `string` | Yes | — | Full Google search URL to scrape |
377
- | `raw` | `boolean` | No | `false` | When true, returns a raw payload (for example HTML) from the API |
378
- | `timeoutMs` | `number` | No | `300000` | Overall request timeout in milliseconds |
379
- | `token` | `string` | No | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
380
-
381
- **Returns:** `Promise<unknown>` — the API response (shape depends on `raw` and server version).
382
-
383
- ---
384
-
385
- ## Trying the SDK locally
386
-
387
- From a clone of this repository, build and run the Google SERP smoke script (requires `MRSCRAPER_API_TOKEN`):
120
+ The defaults are `https://example.com` for `fetch_content` and `python web scraping` for `google_serp`. Pass a different page URL and search query (or Google search URL) after `--`:
388
121
 
389
122
  ```bash
390
- export MRSCRAPER_API_TOKEN=your_token_here
391
- npm install
392
- npm run test:serp
123
+ npm run test:manual -- "https://example.com/page" "iphone 17"
393
124
  ```
394
125
 
395
- The script prints a truncated response so long HTML does not flood the terminal.
396
-
397
- ---
398
-
399
- ## TypeScript
400
-
401
- All option interfaces and shared types are exported for use in your own code:
402
-
403
- ```typescript
404
- import type {
405
- FetchHtmlOptions,
406
- CreateAiScraperOptions,
407
- RerunAiScraperOptions,
408
- BulkRerunAiScraperOptions,
409
- RerunManualScraperOptions,
410
- BulkRerunManualScraperOptions,
411
- GetAllResultsOptions,
412
- GetResultByIdOptions,
413
- GoogleSerpOptions,
414
- ScraperAgent,
415
- SortField,
416
- SortOrder,
417
- } from "@mrscraper/sdk";
418
- ```
419
- ## Compliance & Legal Risk
420
- > **WARNING**
421
- > Scraping login-protected pages carries serious legal and compliance risks. Many websites explicitly prohibit automated access in their Terms of Service, and bypassing authentication to scrape content may expose you to legal action including lawsuits, account termination, and financial penalties. By proceeding on scraping login-protected pages, you confirm that you have read and understood the target website's Terms of Service, and you fully accept all legal, financial, and ethical responsibility for your actions.
422
- ---
126
+ The script prints each HTTP status and a short preview of its response. It exits with a failure status if either call fails.
423
127
 
424
128
  ## License
425
129
 
426
- MIT — see [LICENSE](./LICENSE)
130
+ MIT — see [LICENSE](./LICENSE).