@mrscraper/sdk 1.1.4 → 3.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,154 @@
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
-
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)
34
-
35
- ---
36
-
37
- ## Installation
38
-
39
- ```bash
40
- npm install @mrscraper/sdk
41
- ```
42
-
43
- ## Requirements
44
2
 
45
- - Node.js >= 18
46
- - Your project must use ES Modules. Add `"type": "module"` to your `package.json`:
3
+ ![](./mrscraper.jpeg)
47
4
 
48
- ## Authentication
5
+ Node.js SDK for [MrScraper](https://mrscraper.com) content fetching and Google search results. Requires Node.js 18 or newer and ES modules.
49
6
 
50
- Get your API token from your [MrScraper dashboard](https://app.mrscraper.com) and set it as an environment variable:
7
+ ## Install and authenticate
51
8
 
52
9
  ```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
- ---
87
-
88
- ## Error Handling
89
-
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`.
91
-
92
- ```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
- ```
104
-
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
128
- });
10
+ npm install @mrscraper/sdk
11
+ export MRSCRAPER_API_TOKEN="YOUR_TOKEN"
129
12
  ```
130
13
 
131
- **Options:**
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`.
132
15
 
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 |
16
+ ## Version 3 migration
140
17
 
141
- **Returns:** `Promise<string>` — the raw HTML (or JSON string) of the page.
18
+ Version 3 renames the public functions and their option types. Update your imports and calls:
142
19
 
143
- ---
20
+ | Version 2 | Version 3 |
21
+ |-----------|-----------|
22
+ | `fetch_content(url, options)` | `scraper_api(url, options)` |
23
+ | `google_serp(queryOrUrl, options)` | `web_search(queryOrUrl, options)` |
24
+ | `FetchContentOptions` | `ScraperApiOptions` |
25
+ | `GoogleSerpOptions` | `WebSearchOptions` |
144
26
 
145
- ### `createAiScraper`
27
+ The version 2 names are no longer exported. Request options, API endpoints, and the `{ status_code, data, headers }` response wrapper are unchanged.
146
28
 
147
- Creates a new AI scraper. Supports three agent types:
29
+ If upgrading from version 1, `fetchHtml`, `googleSerp`, and all AI scraper, manual scraper, and results methods were removed in version 2. Use the version 3 functions above; they return a response wrapper instead of only the API payload.
148
30
 
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
31
+ ## Fetch content
152
32
 
153
33
  ```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
- });
34
+ import { scraper_api } from "@mrscraper/sdk";
161
35
 
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
36
+ const result = await scraper_api("https://example.com", {
37
+ html: true,
38
+ markdown: true,
39
+ screenshot: true,
40
+ super: true,
171
41
  });
42
+ console.log(result.status_code, result.data);
172
43
  ```
173
44
 
174
- **Options:**
175
-
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 (map agent) |
183
- | `maxPages` | `number` | No | `50` | Max pages to crawl (map agent) |
184
- | `limit` | `number` | No | `1000` | Max results to return (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 |
188
-
189
- **Returns:** `Promise<unknown>` — the API response object.
190
-
191
- ---
192
-
193
- ### `rerunAiScraper`
194
-
195
- Reruns an existing AI scraper on a new URL.
45
+ `scraper_api` 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.
46
+
47
+ | Option | Default | Description |
48
+ |--------|---------|-------------|
49
+ | `url` | Required first argument | Page URL |
50
+ | `token` | Environment variable | API token override |
51
+ | `html`, `markdown` | `true`, `false` | Request HTML, Markdown, or both |
52
+ | `timeout` | `120` | Page timeout in seconds, from 1 to 300; HTTP timeout is 30 seconds longer |
53
+ | `geo_code`, `proxy_country` | `"US"`, unset | Geolocation and optional proxy country |
54
+ | `browser_rendering` | unset | `true` to force a browser, `false` to disable it, unset for automatic fallback |
55
+ | `screenshot` | `false` | Capture a screenshot and force browser rendering |
56
+ | `super` | `false` | Enable real device routing |
57
+ | `use_proxy`, `proxy` | `true`, unset | Allow a proxy or supply `username:password@host:port` |
58
+ | `home_page` | `false` | Visit the site's root first; sends `warmStart=true` |
59
+ | `wait_for_selector` | unset | Wait for a CSS selector |
60
+ | `block_resources`, `bypass_proxy` | `false`, `false` | Block resources or enable proxy bypass behavior |
61
+ | `cookie_jar`, `headers` | unset | Cookie configuration and target request headers; `headers` accepts an object or JSON string |
62
+ | `max_retries`, `token_cap` | `3`, unset | Retry count and optional token budget |
63
+ | `stream` | unset | Request a streamed response, buffered into the normal return value |
64
+ | `discard_token_secret` | `""` | Value for the `x-discard-token-secret` API header |
65
+
66
+ Unset optional query parameters are omitted. Explicit `false`, `0`, and empty strings are preserved where the Python client sends them.
67
+
68
+ ## Web search
196
69
 
197
70
  ```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
71
+ import { web_search } from "@mrscraper/sdk";
72
+
73
+ const result = await web_search("python web scraping", {
74
+ raw: false,
75
+ region: "us",
76
+ language: "en",
77
+ page: 1,
78
+ format: "json",
206
79
  });
80
+ console.log(result.data);
207
81
  ```
208
82
 
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 (map agent) |
216
- | `maxPages` | `number` | No | `50` | Max pages to process (map and listing agent) |
217
- | `limit` | `number` | No | `1000` | Max results limit (map agent) |
218
- | `includePatterns` | `string` | No | `""` | URL patterns to include (map agent) |
219
- | `excludePatterns` | `string` | No | `""` | URL patterns to exclude (map agent) |
220
- | `token` | `string` | No | — | Overrides the `MRSCRAPER_API_TOKEN` environment variable |
83
+ `web_search` 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`.
221
84
 
222
- **Returns:** `Promise<unknown>` — the API response object.
85
+ | Option | Default | Description |
86
+ |--------|---------|-------------|
87
+ | `url` | Required first argument | Search query or Google search URL |
88
+ | `token` | Environment variable | API token override |
89
+ | `raw` | `true` | Request HTML when true |
90
+ | `format` | `"json"` | `"json"` or `"html"` when `raw` is false |
91
+ | `region`, `language` | unset | Country and language |
92
+ | `page` | unset | One based result page |
93
+ | `render_js` | `false` | Render JavaScript features |
94
+ | `timeout` | `600` | HTTP request timeout in seconds |
223
95
 
224
- ---
96
+ ## Errors and types
225
97
 
226
- ### `bulkRerunAiScraper`
227
-
228
- Reruns an AI scraper on multiple URLs at once.
98
+ 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
99
 
230
100
  ```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
- ```
239
-
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.
101
+ import { scraper_api, MrScraperError } from "@mrscraper/sdk";
102
+ import type { ScraperApiOptions, WebSearchOptions, MrScraperResponse } from "@mrscraper/sdk";
249
103
 
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
- });
104
+ try {
105
+ const result: MrScraperResponse = await scraper_api("https://example.com");
106
+ console.log(result.data);
107
+ } catch (error) {
108
+ if (error instanceof MrScraperError) {
109
+ console.error(error.status, error.message);
110
+ } else {
111
+ throw error;
112
+ }
113
+ }
315
114
  ```
316
115
 
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`
116
+ ## Develop
338
117
 
339
- Fetches a single scraping result by its ID.
340
-
341
- ```typescript
342
- const result = await getResultById({ resultId: "your-result-id" });
343
- console.log(result);
118
+ ```bash
119
+ npm ci
120
+ npm test
121
+ npm run build
344
122
  ```
345
123
 
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.
354
-
355
- ---
124
+ `npm test` uses mocked HTTP responses and does not require an API token.
356
125
 
357
- ### `googleSerp`
126
+ ## Publish manually to npm
358
127
 
359
- Calls the synchronous Google SERP endpoint on the sync scraper API. Authenticates with a **Bearer** token (same token as `MRSCRAPER_API_TOKEN`).
128
+ Version `3.0.0` is a major release because the public API names changed. Both `package.json` and `package-lock.json` already contain this version.
360
129
 
361
- ```typescript
362
- import { googleSerp } from "@mrscraper/sdk";
130
+ From the repository root, verify the package before publishing:
363
131
 
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
- });
132
+ ```bash
133
+ npm ci
134
+ npm test
135
+ npm publish --dry-run --access public
370
136
  ```
371
137
 
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`):
138
+ Review the dry-run file list, then log in with an npm account that has publishing access to `@mrscraper/sdk`:
388
139
 
389
140
  ```bash
390
- export MRSCRAPER_API_TOKEN=your_token_here
391
- npm install
392
- npm run test:serp
141
+ npm login
142
+ npm whoami
143
+ npm publish --access public
144
+ npm view @mrscraper/sdk@3.0.0 version
145
+ npm view @mrscraper/sdk dist-tags --json
393
146
  ```
394
147
 
395
- The script prints a truncated response so long HTML does not flood the terminal.
396
-
397
- ---
398
-
399
- ## TypeScript
148
+ Complete npm's browser login and two-factor authentication prompts. The `prepublishOnly` script cleans and rebuilds `dist` before publishing. A successful publish makes `3.0.0` available under the `latest` tag by default. Each package version can only be published once.
400
149
 
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
- ---
150
+ See npm's [scoped package publishing guide](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages/) and [semantic versioning guide](https://docs.npmjs.com/about-semantic-versioning/).
423
151
 
424
152
  ## License
425
153
 
426
- MIT — see [LICENSE](./LICENSE)
154
+ MIT — see [LICENSE](./LICENSE).