@trawlme/skills 1.4.11 → 1.4.13
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/package.json
CHANGED
|
@@ -127,7 +127,7 @@ try {
|
|
|
127
127
|
One run has a **time budget**: about **10 minutes**. Count it from before your script starts: a scheduled or web-app run may queue for a worker first, inside that budget, and the guard below leaves about 3 minutes for it. A run you wait on through the API (`trawl scraps trigger --wait`, the n8n node) starts its 10 minutes when your script starts instead; keep the guard anyway, the same script also runs on a schedule. Past it the worker stops the run and nothing is returned. Time is almost always the limit, not size: the whole output may reach tens of MB before a run fails with `output too large`.
|
|
128
128
|
|
|
129
129
|
- Add a **deadline guard**: note `Date.now()` at the start, stop about **7 minutes** in, and `returnData` the rows read so far, with `truncated: true` on the last one (the platform reads it as a marker that the run stopped early, not as a data column). The guard runs between requests, so also give each request its own timeout (e.g. `fetch(url, { signal: AbortSignal.timeout(20000) })` inside `page.evaluate`, with a `try`/`catch` that breaks the loop): one stuck page must not carry the run past its budget.
|
|
130
|
-
- Read fewer, cheaper pages: each `page.goto` costs seconds on its own. For lists, prefer same-origin `fetch` from inside the page (`page.evaluate`) on JSON feeds, pagination or search APIs, sitemaps. One request at a time, never parallel tabs or `page.goto`s to the same site (several loads within a few seconds can get the run blocked).
|
|
130
|
+
- Read fewer, cheaper pages: each `page.goto` costs seconds on its own. For lists, prefer same-origin `fetch` from inside the page (`page.evaluate`) on JSON feeds, pagination or search APIs, sitemaps. One request at a time, never parallel tabs or `page.goto`s to the same site (several loads within a few seconds can get the run blocked). Between two requests to the same host, wait a random pause of 1.5 s or more (`1500 + Math.random() * 1000` ms), never a fixed one: that pause is rate-limit politeness (`references/anti-patterns.md`), never an anti-bot mechanism, never a wait for the page.
|
|
131
131
|
- A catalog that cannot fit one run is still scrapable:
|
|
132
132
|
- **targeted** — only the items you need, by search or by their URLs (passed as a param), not the whole catalog;
|
|
133
133
|
- **split** — one scrap per category or section, each small enough for one run; each scrap keeps its own rows. Slices of ONE scrap across runs (a different param per run) replace each other's rows, unless the scrap's `items` option keeps them (`keepData`, set by the Trawl team on request).
|
|
@@ -142,7 +142,7 @@ for (const url of productUrls) { // your list, e.g. from a param or a sitemap
|
|
|
142
142
|
break;
|
|
143
143
|
}
|
|
144
144
|
// … fetch one product (awaited), push it to rows
|
|
145
|
-
await new Promise((r) => setTimeout(r, 1000)); // politeness between requests
|
|
145
|
+
await new Promise((r) => setTimeout(r, 1500 + Math.random() * 1000)); // politeness between requests
|
|
146
146
|
}
|
|
147
147
|
returnData(rows);
|
|
148
148
|
```
|
|
@@ -172,6 +172,10 @@ Full detail in `references/anti-patterns.md`. Summary:
|
|
|
172
172
|
|
|
173
173
|
Some pages hide data behind real UI interactions — scroll, hover, click, form fill. These are about **functional correctness**, not bot evasion. See `references/interaction-patterns.md` for patterns: lazy-load scroll, hover-to-reveal, click-to-expand, `page.type` form fill, state-transition waits, "next" pagination.
|
|
174
174
|
|
|
175
|
+
## Script helpers (`fetch`, `cursor`, `captcha`)
|
|
176
|
+
|
|
177
|
+
Besides `page` and `returnData`, a script on the worker can call `fetch` (a request from the script, outside the page: no page cookies), `cursor` (mouse moves along a path, for hover menus and controls that need a real pointer) and `captcha` (a token for a captcha inside a form the script submits). See `references/script-helpers.md` for each helper's arguments, return shape and an example, and the full list of globals a script can use.
|
|
178
|
+
|
|
175
179
|
## Canonical Trawl docs
|
|
176
180
|
|
|
177
181
|
- *Trawl Scraping docs (in-app help center)* — selector basics, `returnData`, scrap lifecycle.
|
|
@@ -22,7 +22,7 @@ Source: [browser-use.com/posts/bot-detection](https://browser-use.com/posts/bot-
|
|
|
22
22
|
|
|
23
23
|
## No random jitter as primary defence
|
|
24
24
|
|
|
25
|
-
Bot detection decides at the fingerprint level — milliseconds before any timing signal exists. `Math.random() * 500` delays have no effect.
|
|
25
|
+
Bot detection decides at the fingerprint level — milliseconds before any timing signal exists. `Math.random() * 500` delays have no effect. A random pause of 1.5 s or more between two requests to the same host (`1500 + Math.random() * 1000` ms, never a fixed one, never shorter) is for **rate-limit politeness** only, never an anti-bot mechanism.
|
|
26
26
|
|
|
27
27
|
Source: [browser-use.com/posts/bot-detection](https://browser-use.com/posts/bot-detection)
|
|
28
28
|
|
|
@@ -30,7 +30,7 @@ Source: [browser-use.com/posts/bot-detection](https://browser-use.com/posts/bot-
|
|
|
30
30
|
|
|
31
31
|
## No fixed setTimeout / waitForTimeout
|
|
32
32
|
|
|
33
|
-
`page.waitForTimeout(N)` is deprecated. `setTimeout` is unreliable under load and slows every run unconditionally. The one exception is the
|
|
33
|
+
`page.waitForTimeout(N)` is deprecated. `setTimeout` is unreliable under load and slows every run unconditionally. The one exception is the random pause of 1.5 s or more between two requests to the same host (rate-limit politeness, see Run budget in the skill), never a wait for the page. Use state-based waits:
|
|
34
34
|
- `page.waitForSelector(selector)` — most targeted
|
|
35
35
|
- `page.waitForNetworkIdle()` — for SPA-heavy pages
|
|
36
36
|
- `page.waitForFunction(fn)` — for complex DOM conditions
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# Script Helpers — Trawl Scrap Scripts
|
|
2
|
+
|
|
3
|
+
> *Besides `page`, `browser`, `TRAWL` and `returnData`, a script on the worker can call four helpers: `fetch`, `cursor`, `captcha` and `trawl.waitForHydration`. This page lists what each one takes and returns. They exist on the worker only: the local harness (`trawl-scrap-local-test`) does not inject `cursor`, `captcha` or `trawl`, so a script that uses them fails locally with a `ReferenceError`.*
|
|
4
|
+
|
|
5
|
+
The script runs in a sandbox, not in Node. Only these globals exist at script level: `page`, `browser`, `cursor`, `captcha`, `TRAWL`, `account`, `trawl`, `saveSession`, `returnData`, `fetch`, `console`, the timers (`setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`), `JSON`, `Math`, `Date`, `Array`, `Object`, `String`, `Number`, `Boolean`, `RegExp`, `Map`, `Set`, `Promise`, `Error`, `URL`, `URLSearchParams`, `Buffer`. Anything else (`AbortSignal`, `AbortController`, `Headers`, `FormData`, `TextDecoder`, `require`, `process`) is undefined at script level; it is still there inside `page.evaluate`, which runs in the browser.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## `fetch` — a request from the script, not from the page
|
|
10
|
+
|
|
11
|
+
`fetch(url, options?)` → `Promise<Response>`. The standard `fetch`: same arguments, same `Response` (`res.ok`, `res.status`, `await res.json()`, `await res.text()`).
|
|
12
|
+
|
|
13
|
+
It runs on the worker, **outside the page**: it does not carry the page's cookies, session or headers, and does not go the way the page's own requests go. So:
|
|
14
|
+
|
|
15
|
+
- **For the target site, keep using `fetch` inside `page.evaluate`** (see "Run budget" in `SKILL.md`): same origin, same cookies, same session as the page.
|
|
16
|
+
- **Use the script-level `fetch` for a public endpoint that needs no page**: a sitemap, a public JSON feed, a file you then parse in the script.
|
|
17
|
+
|
|
18
|
+
`AbortSignal` does not exist at script level, so bound the wait with `Promise.race`:
|
|
19
|
+
|
|
20
|
+
```js
|
|
21
|
+
// one request, at most 20 s — the request itself is not cancelled, the script just stops waiting
|
|
22
|
+
const withTimeout = (p, ms) => Promise.race([
|
|
23
|
+
p,
|
|
24
|
+
new Promise((_, reject) => setTimeout(() => reject(new Error(`timeout after ${ms} ms`)), ms)),
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
let urls = [];
|
|
28
|
+
try {
|
|
29
|
+
// bound the headers AND the body read: a server can send headers, then stall
|
|
30
|
+
const xml = await withTimeout(
|
|
31
|
+
fetch('https://example.com/sitemap.xml').then((res) => (res.ok ? res.text() : '')),
|
|
32
|
+
20000,
|
|
33
|
+
);
|
|
34
|
+
urls = [...xml.matchAll(/<loc>([^<]+)<\/loc>/g)].map((m) => m[1]);
|
|
35
|
+
} catch (err) {
|
|
36
|
+
console.error('sitemap fetch failed:', err.message);
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## `cursor` — a mouse that moves along a path
|
|
43
|
+
|
|
44
|
+
`cursor` drives the mouse of the main `page` along a curved path instead of jumping to the target. Use it for pages that react to real pointer movement: a menu that opens on hover, a control that ignores `element.click()`. It is bound to the main `page` only; a tab you open with `browser.newPage()` has no cursor. `page.click()` and `page.hover()` do not use it.
|
|
45
|
+
|
|
46
|
+
Every method returns `Promise<void>`. `target` is a CSS selector, an XPath, or an element handle.
|
|
47
|
+
|
|
48
|
+
| Method | What it does |
|
|
49
|
+
|---|---|
|
|
50
|
+
| `cursor.click(target?, options?)` | Moves to `target` (scrolling it into view), then clicks. No `target` = click where the mouse is. Options: `button` (`'left'`), `clickCount` (`1`), `hesitate` (ms before the click), `waitForClick` (ms between press and release), `moveDelay` (pause after the move, random from 0 up to this, default 2000 ms). |
|
|
51
|
+
| `cursor.move(target, options?)` | Moves to `target` (hover), scrolling it into view first. Options: `moveDelay`, `moveSpeed`, `paddingPercentage` (how far inside the element to aim). |
|
|
52
|
+
| `cursor.moveTo({ x, y }, options?)` | Moves to a point in the viewport. |
|
|
53
|
+
| `cursor.scrollIntoView(target, options?)` | Scrolls until `target` is visible; no scroll if it already is. |
|
|
54
|
+
| `cursor.scroll({ x?, y? }, options?)` | Scrolls by that many pixels. |
|
|
55
|
+
| `cursor.getLocation()` | Returns the current `{ x, y }` (not a promise). |
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
// open a hover menu, then read the links it reveals
|
|
59
|
+
const MENU_SEL = 'nav [aria-haspopup="true"]'; // the menu trigger
|
|
60
|
+
const ITEM_SEL = 'nav [role="menu"] a'; // links shown once open
|
|
61
|
+
await page.waitForSelector(MENU_SEL);
|
|
62
|
+
await cursor.move(MENU_SEL);
|
|
63
|
+
await page.waitForSelector(ITEM_SEL, { visible: true });
|
|
64
|
+
const links = await page.$$eval(ITEM_SEL, (els) => els.map((a) => a.href));
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
## `trawl.waitForHydration` — wait until the page has finished loading its data
|
|
70
|
+
|
|
71
|
+
Waits on the last page the script navigated. Use it after `page.goto` on a site that renders its content with JavaScript, before you read the DOM.
|
|
72
|
+
|
|
73
|
+
| Option | Default | Meaning |
|
|
74
|
+
|---|---|---|
|
|
75
|
+
| `strategy` | `'networkIdle'` | `'networkIdle'`: no network request for 500 ms. `'selector'`: wait for `selector` to appear. |
|
|
76
|
+
| `selector` | — | Required with `strategy: 'selector'` (throws without it). |
|
|
77
|
+
| `timeout` | `30000` | Milliseconds before it throws. |
|
|
78
|
+
|
|
79
|
+
Returns nothing; throws on timeout.
|
|
80
|
+
|
|
81
|
+
```js
|
|
82
|
+
await page.goto(TRAWL.url, { waitUntil: 'domcontentloaded' });
|
|
83
|
+
await trawl.waitForHydration({ strategy: 'selector', selector: '.product-card', timeout: 45000 });
|
|
84
|
+
const items = await page.$$eval('.product-card', (cards) => cards.map((c) => ({ title: c.textContent.trim() })));
|
|
85
|
+
return returnData(items);
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## `captcha` — get a token for a captcha the script must submit
|
|
89
|
+
|
|
90
|
+
The worker already handles the common challenge pages by itself, after your script runs (see `anti-patterns.md`: never detect or fight them in your script). `captcha` is for one case only: a captcha that is **part of a form the script fills and submits** (a search or lookup form that asks for a token before it answers).
|
|
91
|
+
|
|
92
|
+
Each solver takes the widget's site key and the page URL and returns `Promise<string>`, the token. It **throws** when solving is not available on the worker, fails, or takes too long. A solve can take from seconds to a few minutes, and that time counts against the run budget (`SKILL.md`, "Run budget"): always `try`/`catch` it and keep the deadline guard.
|
|
93
|
+
|
|
94
|
+
| Helper | Arguments | Returns |
|
|
95
|
+
|---|---|---|
|
|
96
|
+
| `captcha.solveRecaptchaV2(siteKey, pageUrl)` | site key (`data-sitekey` on the widget), page URL | `Promise<string>` token |
|
|
97
|
+
| `captcha.solveRecaptchaV3(siteKey, pageUrl, action?, minScore?)` | site key, page URL, the page's action name (default `'verify'`), minimum score (default `0.7`) | `Promise<string>` token |
|
|
98
|
+
| `captcha.solveHcaptcha(siteKey, pageUrl)` | site key, page URL | `Promise<string>` token |
|
|
99
|
+
| `captcha.solveTurnstile(siteKey, pageUrl)` | site key, page URL | `Promise<string>` token |
|
|
100
|
+
| `captcha.injectRecaptchaSolution(page, token)` | the page, a reCAPTCHA token | `Promise<void>`: writes the token into `#g-recaptcha-response` and calls the widget's callbacks |
|
|
101
|
+
|
|
102
|
+
Only reCAPTCHA has an inject helper. For the others, write the token into the widget's response field yourself (`[name="h-captcha-response"]` for hCaptcha, `[name="cf-turnstile-response"]` for Turnstile), then submit the form.
|
|
103
|
+
|
|
104
|
+
```js
|
|
105
|
+
// a lookup form protected by a reCAPTCHA v2 checkbox
|
|
106
|
+
const FORM_SEL = 'form#lookup';
|
|
107
|
+
const WIDGET_SEL = '.g-recaptcha[data-sitekey]';
|
|
108
|
+
await page.type(`${FORM_SEL} input[name="q"]`, TRAWL.query);
|
|
109
|
+
try {
|
|
110
|
+
const siteKey = await page.$eval(WIDGET_SEL, (el) => el.getAttribute('data-sitekey'));
|
|
111
|
+
const token = await captcha.solveRecaptchaV2(siteKey, page.url());
|
|
112
|
+
await captcha.injectRecaptchaSolution(page, token);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
console.error('captcha step failed:', err.message);
|
|
115
|
+
returnData([]); // nothing to read without the form's answer
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
await Promise.all([
|
|
119
|
+
page.waitForNavigation({ waitUntil: 'domcontentloaded' }),
|
|
120
|
+
page.click(`${FORM_SEL} [type="submit"]`),
|
|
121
|
+
]);
|
|
122
|
+
```
|