@brightdata/facebook-scraper 0.0.0-stage → 0.0.1
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/LICENSE +202 -0
- package/README.md +981 -2
- package/package.json +37 -4
- package/src/cli.js +127 -0
- package/src/index.js +47 -0
- package/src/scrape.js +412 -0
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@brightdata/facebook-scraper",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.1",
|
|
4
|
+
"description": "Facebook scraper in JavaScript: page and group posts, comments, reels, pages, profiles, reviews, Marketplace, events and the Meta Ad Library, as JSON, on the Bright Data Facebook Scraper API. No Facebook login, no browser, no dependencies. 5,000 free credits a month.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "Apache-2.0",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20"
|
|
9
|
+
},
|
|
10
|
+
"main": "src/index.js",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": "./src/index.js"
|
|
13
|
+
},
|
|
14
|
+
"bin": {
|
|
15
|
+
"facebook-scraper": "src/cli.js"
|
|
16
|
+
},
|
|
17
|
+
"files": [
|
|
18
|
+
"src"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "node --test",
|
|
22
|
+
"lint": "oxlint src tests"
|
|
23
|
+
},
|
|
24
|
+
"devDependencies": {
|
|
25
|
+
"oxlint": "^1.83.0"
|
|
26
|
+
},
|
|
27
|
+
"repository": {
|
|
28
|
+
"type": "git",
|
|
29
|
+
"url": "git+https://github.com/brightdata/facebook-scraper-node.git"
|
|
30
|
+
},
|
|
31
|
+
"bugs": {
|
|
32
|
+
"url": "https://github.com/brightdata/facebook-scraper-node/issues"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://github.com/brightdata/facebook-scraper-node#readme",
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public",
|
|
37
|
+
"provenance": false
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/cli.js
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** facebook-scraper Meta Microsoft */
|
|
3
|
+
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
|
|
8
|
+
import { TokenMissing, scrapePage, token, write } from "./scrape.js";
|
|
9
|
+
|
|
10
|
+
const USAGE = `usage: facebook-scraper PAGE [PAGE ...] [--limit N] [--out PATH]
|
|
11
|
+
|
|
12
|
+
PAGE a page name or URL, such as Meta or facebook.com/Meta
|
|
13
|
+
--limit N posts per page, default 5, minimum 1
|
|
14
|
+
--out PATH output file, default facebook.json`;
|
|
15
|
+
|
|
16
|
+
const FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
17
|
+
|
|
18
|
+
const CLEAR_LINE = "\r\x1b[2K";
|
|
19
|
+
|
|
20
|
+
/** Seconds as h:mm:ss, the shape a reader can read at a glance. */
|
|
21
|
+
function clock(seconds) {
|
|
22
|
+
const mm = String(Math.floor(seconds / 60) % 60).padStart(2, "0");
|
|
23
|
+
const ss = String(seconds % 60).padStart(2, "0");
|
|
24
|
+
return `${Math.floor(seconds / 3600)}:${mm}:${ss}`;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* A spinner and a running clock, so minutes of waiting look alive.
|
|
29
|
+
* Outside a terminal it prints one plain line instead, because a log wants a
|
|
30
|
+
* line, not an animation.
|
|
31
|
+
*/
|
|
32
|
+
function waiting(label) {
|
|
33
|
+
if (!process.stdout.isTTY) {
|
|
34
|
+
process.stdout.write(`asking ${label}...\n`);
|
|
35
|
+
return () => {};
|
|
36
|
+
}
|
|
37
|
+
const started = Date.now();
|
|
38
|
+
let frame = 0;
|
|
39
|
+
const tick = () => {
|
|
40
|
+
const spin = FRAMES[frame++ % FRAMES.length];
|
|
41
|
+
process.stdout.write(`${CLEAR_LINE}${spin} ${label} ${clock(Math.floor((Date.now() - started) / 1000))}`);
|
|
42
|
+
};
|
|
43
|
+
tick();
|
|
44
|
+
const timer = setInterval(tick, 100);
|
|
45
|
+
timer.unref();
|
|
46
|
+
return () => {
|
|
47
|
+
clearInterval(timer);
|
|
48
|
+
process.stdout.write(CLEAR_LINE); // leave the line clean for the result
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Reject a limit the API would charge for and not honour. */
|
|
53
|
+
function positive(value) {
|
|
54
|
+
const number = Number(value);
|
|
55
|
+
if (!Number.isInteger(number) || number < 1) throw new Error(`${value} is not 1 or more`);
|
|
56
|
+
return number;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function main(argv = process.argv.slice(2)) {
|
|
60
|
+
let pages;
|
|
61
|
+
let limit;
|
|
62
|
+
let out;
|
|
63
|
+
try {
|
|
64
|
+
const { values, positionals } = parseArgs({
|
|
65
|
+
args: argv,
|
|
66
|
+
options: { limit: { type: "string" }, out: { type: "string" } },
|
|
67
|
+
allowPositionals: true,
|
|
68
|
+
});
|
|
69
|
+
pages = positionals;
|
|
70
|
+
limit = values.limit === undefined ? 5 : positive(values.limit);
|
|
71
|
+
out = values.out ?? "facebook.json";
|
|
72
|
+
if (!pages.length) throw new Error("give at least one page");
|
|
73
|
+
} catch (error) {
|
|
74
|
+
process.stderr.write(`${error.message}\n\n${USAGE}\n`);
|
|
75
|
+
return 2;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
process.stdout.write(
|
|
79
|
+
`Fetching up to ${limit} recent posts per page, for: ${pages.join(", ")}\n` +
|
|
80
|
+
"Usually one to three minutes each. Billed per post, 5,000 free credits a month.\n",
|
|
81
|
+
);
|
|
82
|
+
try {
|
|
83
|
+
token(); // fail before the first wait, not after it
|
|
84
|
+
} catch (error) {
|
|
85
|
+
if (!(error instanceof TokenMissing)) throw error;
|
|
86
|
+
process.stderr.write(`${error.message}\n`);
|
|
87
|
+
return 2;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const outcomes = [];
|
|
91
|
+
for (const page of pages) {
|
|
92
|
+
const done = waiting(page);
|
|
93
|
+
const outcome = await scrapePage(page, { limit });
|
|
94
|
+
done();
|
|
95
|
+
process.stdout.write(`${outcome.line()}\n`);
|
|
96
|
+
outcomes.push(outcome);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
await write(outcomes, out);
|
|
100
|
+
const found = outcomes.flatMap((outcome) => outcome.posts);
|
|
101
|
+
const fields = found.length ? ` (${Object.keys(found[0]).length} fields per post)` : "";
|
|
102
|
+
// the path as typed, not resolved: the reader knows where they ran it
|
|
103
|
+
process.stdout.write(`\nSaved ${found.length} posts as JSON to ${out}${fields}\n`);
|
|
104
|
+
return outcomes.every((outcome) => outcome.ok) ? 0 : 1;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Is this file the program being run?
|
|
109
|
+
*
|
|
110
|
+
* Comparing `import.meta.url` to `file://${argv[1]}` is wrong twice over. A
|
|
111
|
+
* path with a space encodes to %20 on one side only, and `npm install -g`
|
|
112
|
+
* puts a symlink on PATH, so argv[1] is the link while import.meta.url is the
|
|
113
|
+
* file it points at. Either mismatch makes the installed command exit 0 and
|
|
114
|
+
* do nothing at all.
|
|
115
|
+
*/
|
|
116
|
+
function isEntryPoint() {
|
|
117
|
+
if (!process.argv[1]) return false;
|
|
118
|
+
try {
|
|
119
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
120
|
+
} catch {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (isEntryPoint()) {
|
|
126
|
+
process.exitCode = await main();
|
|
127
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A Facebook scraper on Bright Data's Scraper API. */
|
|
2
|
+
|
|
3
|
+
export {
|
|
4
|
+
AD_LIBRARY,
|
|
5
|
+
ApiError,
|
|
6
|
+
CANCELLED,
|
|
7
|
+
COMMENTS,
|
|
8
|
+
EVENTS,
|
|
9
|
+
GROUP_POSTS,
|
|
10
|
+
MARKETPLACE,
|
|
11
|
+
Outcome,
|
|
12
|
+
PAGE_POSTS,
|
|
13
|
+
PAGES,
|
|
14
|
+
POSTS,
|
|
15
|
+
PROFILES,
|
|
16
|
+
REELS,
|
|
17
|
+
REVIEWS,
|
|
18
|
+
TokenMissing,
|
|
19
|
+
ads,
|
|
20
|
+
adsSearch,
|
|
21
|
+
comments,
|
|
22
|
+
events,
|
|
23
|
+
eventsByVenue,
|
|
24
|
+
eventsSearch,
|
|
25
|
+
fetchSnapshot,
|
|
26
|
+
groupPosts,
|
|
27
|
+
marketplace,
|
|
28
|
+
marketplaceCategory,
|
|
29
|
+
marketplaceSearch,
|
|
30
|
+
pagePosts,
|
|
31
|
+
pageUrl,
|
|
32
|
+
pages,
|
|
33
|
+
posts,
|
|
34
|
+
profiles,
|
|
35
|
+
reels,
|
|
36
|
+
reviews,
|
|
37
|
+
run,
|
|
38
|
+
scrape,
|
|
39
|
+
scrapePage,
|
|
40
|
+
split,
|
|
41
|
+
status,
|
|
42
|
+
token,
|
|
43
|
+
trigger,
|
|
44
|
+
write,
|
|
45
|
+
} from "./scrape.js";
|
|
46
|
+
|
|
47
|
+
export const VERSION = "0.0.1";
|
package/src/scrape.js
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Facebook pages, posts, comments, Marketplace, events and ads on the Bright Data Scraper API, with fetch.
|
|
3
|
+
*
|
|
4
|
+
* page URL -> trigger -> poll progress -> fetch snapshot -> records
|
|
5
|
+
*
|
|
6
|
+
* No dependencies. The JavaScript SDK, `@brightdata/sdk` 1.2.0, wraps nine of
|
|
7
|
+
* these eleven scrapers, not page details or the Ad Library, so this module
|
|
8
|
+
* talks to the API over HTTP and covers all eleven. Every call
|
|
9
|
+
* is an asynchronous job: trigger it, poll until the snapshot is ready,
|
|
10
|
+
* download it. On 2026-11-03 a run took 12 seconds (reviews, one ad) to 234
|
|
11
|
+
* seconds (a Marketplace category).
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readFileSync } from "node:fs";
|
|
15
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { dirname, join, resolve } from "node:path";
|
|
18
|
+
|
|
19
|
+
export const API = "https://api.brightdata.com/datasets/v3";
|
|
20
|
+
|
|
21
|
+
// Every Facebook scraper, by what it returns. All take a `url` input unless noted.
|
|
22
|
+
/** Posts from a page URL. */
|
|
23
|
+
export const PAGE_POSTS = "gd_lkaxegm826bjpoo9m5";
|
|
24
|
+
/** Posts from a public group URL. */
|
|
25
|
+
export const GROUP_POSTS = "gd_lz11l67o2cb3r0lkj3";
|
|
26
|
+
/** One post per post URL. */
|
|
27
|
+
export const POSTS = "gd_lyclm1571iy3mv57zw";
|
|
28
|
+
/** Comments on a post URL. */
|
|
29
|
+
export const COMMENTS = "gd_lkay758p1eanlolqw8";
|
|
30
|
+
/** Reels from a page URL. */
|
|
31
|
+
export const REELS = "gd_lyclm3ey2q6rww027t";
|
|
32
|
+
/** Page details: followers, category, contact info. */
|
|
33
|
+
export const PAGES = "gd_mf124a0511bauquyow";
|
|
34
|
+
/** Public profile details of a person. */
|
|
35
|
+
export const PROFILES = "gd_mf0urb782734ik94dz";
|
|
36
|
+
/** Reviews from a page's /reviews/ URL. */
|
|
37
|
+
export const REVIEWS = "gd_m0dtqpiu1mbcyc2g86";
|
|
38
|
+
/** Event URL, or discover by search URL or venue. */
|
|
39
|
+
export const EVENTS = "gd_m14sd0to1jz48ppm51";
|
|
40
|
+
/** Listing URL, or discover by keyword or category URL. */
|
|
41
|
+
export const MARKETPLACE = "gd_lvt9iwuh6fbcwmx1a";
|
|
42
|
+
/** Meta Ad Library ad URL, or discover by keyword. */
|
|
43
|
+
export const AD_LIBRARY = "gd_mtveskb62h7q65ftgz";
|
|
44
|
+
|
|
45
|
+
/** The slowest run on 2026-11-03 was 234 seconds; the wait outlasts that comfortably. */
|
|
46
|
+
export const TIMEOUT_MS = 900_000;
|
|
47
|
+
|
|
48
|
+
export const NO_TOKEN = [
|
|
49
|
+
"API token required but not found.",
|
|
50
|
+
" export BRIGHTDATA_API_TOKEN=YOUR_API_KEY token: https://brightdata.com/cp/setting/users",
|
|
51
|
+
" or run once: npx -p @brightdata/cli bdata login",
|
|
52
|
+
].join("\n");
|
|
53
|
+
|
|
54
|
+
/** The API refused a request, or a job ended without a snapshot. */
|
|
55
|
+
export class ApiError extends Error {
|
|
56
|
+
name = "ApiError";
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** No token in the environment and no Bright Data CLI login. */
|
|
60
|
+
export class TokenMissing extends ApiError {
|
|
61
|
+
name = "TokenMissing";
|
|
62
|
+
constructor() {
|
|
63
|
+
super(NO_TOKEN);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* The network and the clock, behind one indirection.
|
|
69
|
+
*
|
|
70
|
+
* ES module exports are read-only bindings, so a test cannot replace an
|
|
71
|
+
* imported function. Going through this object lets the offline tests stand
|
|
72
|
+
* in for the API and skip the waits.
|
|
73
|
+
*/
|
|
74
|
+
export const transport = {
|
|
75
|
+
fetch: (...args) => globalThis.fetch(...args),
|
|
76
|
+
pollMs: 10_000,
|
|
77
|
+
sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
|
|
78
|
+
credentialsPath: () => {
|
|
79
|
+
if (process.platform === "win32") {
|
|
80
|
+
return join(process.env.APPDATA ?? join(homedir(), "AppData", "Roaming"), "brightdata-cli", "credentials.json");
|
|
81
|
+
}
|
|
82
|
+
const base = process.platform === "darwin" ? join(homedir(), "Library", "Application Support") : join(homedir(), ".config");
|
|
83
|
+
return join(base, "brightdata-cli", "credentials.json");
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
/** BRIGHTDATA_API_TOKEN, else the Bright Data CLI login. Never a key in code. */
|
|
88
|
+
export function token() {
|
|
89
|
+
const found = (process.env.BRIGHTDATA_API_TOKEN ?? "").trim();
|
|
90
|
+
if (found) return found;
|
|
91
|
+
try {
|
|
92
|
+
const key = JSON.parse(readFileSync(transport.credentialsPath(), "utf8")).api_key;
|
|
93
|
+
if (key) return key;
|
|
94
|
+
} catch {
|
|
95
|
+
// no login file, or not JSON: same as no login
|
|
96
|
+
}
|
|
97
|
+
throw new TokenMissing();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function call(path, body) {
|
|
101
|
+
const response = await transport.fetch(API + path, {
|
|
102
|
+
method: body === undefined ? "GET" : "POST",
|
|
103
|
+
headers: { Authorization: `Bearer ${token()}`, "Content-Type": "application/json" },
|
|
104
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
105
|
+
});
|
|
106
|
+
const text = await response.text();
|
|
107
|
+
if (!response.ok) throw new ApiError(`HTTP ${response.status}: ${text.trim().slice(0, 300)}`);
|
|
108
|
+
return text ? JSON.parse(text) : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Start a job and return its snapshot id. Error rows are always asked for. */
|
|
112
|
+
export async function trigger(datasetId, inputs, { discoverBy, limitPerInput } = {}) {
|
|
113
|
+
const query = new URLSearchParams({ dataset_id: datasetId, include_errors: "true" });
|
|
114
|
+
if (discoverBy) {
|
|
115
|
+
query.set("type", "discover_new");
|
|
116
|
+
query.set("discover_by", discoverBy);
|
|
117
|
+
}
|
|
118
|
+
if (limitPerInput !== undefined) query.set("limit_per_input", String(limitPerInput));
|
|
119
|
+
return (await call(`/trigger?${query}`, inputs)).snapshot_id;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** running, ready or failed. */
|
|
123
|
+
export async function status(snapshotId) {
|
|
124
|
+
return (await call(`/progress/${snapshotId}`)).status;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The rows of a ready snapshot. Snapshots stay downloadable for 30 days. */
|
|
128
|
+
export async function fetchSnapshot(snapshotId) {
|
|
129
|
+
const data = await call(`/snapshot/${snapshotId}?format=json`);
|
|
130
|
+
return (Array.isArray(data) ? data : [data]).filter((row) => row && typeof row === "object");
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* status(), except that a dropped connection is not the end of a paid job.
|
|
135
|
+
*
|
|
136
|
+
* A poll is safe to repeat, and one "fetch failed" five minutes into a job
|
|
137
|
+
* lost it on 2026-10-24. An HTTP error still rejects.
|
|
138
|
+
*/
|
|
139
|
+
async function poll(snapshotId) {
|
|
140
|
+
try {
|
|
141
|
+
return await status(snapshotId);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error instanceof ApiError) throw error;
|
|
144
|
+
return "running";
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Trigger, wait, fetch. Rows the API could not collect carry an `error` key. */
|
|
149
|
+
export async function run(datasetId, inputs, { discoverBy, limitPerInput, timeoutMs = TIMEOUT_MS } = {}) {
|
|
150
|
+
const snapshotId = await trigger(datasetId, inputs, { discoverBy, limitPerInput });
|
|
151
|
+
const deadline = Date.now() + timeoutMs;
|
|
152
|
+
let state;
|
|
153
|
+
while (!["ready", "failed"].includes((state = await poll(snapshotId)))) {
|
|
154
|
+
if (Date.now() > deadline) {
|
|
155
|
+
throw new ApiError(`timeout: snapshot ${snapshotId} not ready after ${Math.round(timeoutMs / 1000)}s`);
|
|
156
|
+
}
|
|
157
|
+
await transport.sleep(transport.pollMs);
|
|
158
|
+
}
|
|
159
|
+
if (state === "failed") throw new ApiError(`snapshot ${snapshotId} failed`);
|
|
160
|
+
return fetchSnapshot(snapshotId);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const many = (value) => (Array.isArray(value) ? value : [value]);
|
|
164
|
+
|
|
165
|
+
/** Only the fields that were actually set. */
|
|
166
|
+
function given(fields) {
|
|
167
|
+
return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined && value !== null));
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** One input per URL, with every field that was actually set. */
|
|
171
|
+
function items(urls, fields = {}) {
|
|
172
|
+
const extra = given(fields);
|
|
173
|
+
return many(urls).map((url) => ({ url, ...extra }));
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Recent posts from Facebook page URLs, `limit` per page.
|
|
178
|
+
*
|
|
179
|
+
* Other options go into each input as the API names them, for example
|
|
180
|
+
* `start_date`, `end_date` or `posts_to_not_include`.
|
|
181
|
+
*/
|
|
182
|
+
export function pagePosts(urls, { limit = 5, ...options } = {}) {
|
|
183
|
+
return run(PAGE_POSTS, items(urls, { num_of_posts: limit, ...options }));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Recent posts from public Facebook group URLs, `limit` per group. */
|
|
187
|
+
export function groupPosts(urls, { limit = 5, ...options } = {}) {
|
|
188
|
+
return run(GROUP_POSTS, items(urls, { num_of_posts: limit, ...options }));
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Full records for Facebook post URLs, one job for the whole list. */
|
|
192
|
+
export function posts(urls) {
|
|
193
|
+
return run(POSTS, items(urls));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Comments on Facebook post URLs. Billed per comment, so set `limit`.
|
|
198
|
+
*
|
|
199
|
+
* The limit is the `limit_records` input. `num_of_comments`, which the Python
|
|
200
|
+
* SDK sends, is rejected by the API as a validation error.
|
|
201
|
+
*/
|
|
202
|
+
export function comments(urls, { limit = 10, ...options } = {}) {
|
|
203
|
+
return run(COMMENTS, items(urls, { limit_records: limit, ...options }));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Recent reels from Facebook page URLs, `limit` per page. */
|
|
207
|
+
export function reels(urls, { limit = 5, ...options } = {}) {
|
|
208
|
+
return run(REELS, items(urls, { num_of_posts: limit, ...options }));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Page details for Facebook page URLs: followers, category, contact info. */
|
|
212
|
+
export function pages(urls) {
|
|
213
|
+
return run(PAGES, items(urls));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Public profile details for Facebook profile URLs of people. */
|
|
217
|
+
export function profiles(urls) {
|
|
218
|
+
return run(PROFILES, items(urls));
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Reviews from a page's reviews URL, such as https://www.facebook.com/TheGarden/reviews/.
|
|
223
|
+
*
|
|
224
|
+
* Many brand pages have reviews turned off and return an error row, "Reviews
|
|
225
|
+
* not found" or a dead page, instead of zero rows.
|
|
226
|
+
*/
|
|
227
|
+
export function reviews(urls, { limit = 10, ...options } = {}) {
|
|
228
|
+
return run(REVIEWS, items(urls, { num_of_reviews: limit, ...options }));
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Full records for Facebook event URLs. */
|
|
232
|
+
export function events(urls) {
|
|
233
|
+
return run(EVENTS, items(urls));
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Events from an events search URL, such as .../events/search/?q=marathon. */
|
|
237
|
+
export function eventsSearch(searchUrls, { limit = 5 } = {}) {
|
|
238
|
+
return run(EVENTS, items(searchUrls), { discoverBy: "url", limitPerInput: limit });
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Events at a venue. Pass the page's /events URL; the bare page URL finds none. */
|
|
242
|
+
export function eventsByVenue(venueUrls, { limit = 5, upcomingOnly = true } = {}) {
|
|
243
|
+
const inputs = items(venueUrls, { upcoming_events_only: upcomingOnly });
|
|
244
|
+
return run(EVENTS, inputs, { discoverBy: "venue", limitPerInput: limit });
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Full records for Facebook Marketplace item URLs. */
|
|
248
|
+
export function marketplace(urls) {
|
|
249
|
+
return run(MARKETPLACE, items(urls));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Marketplace listings for a keyword in a city. `radius` and `date_listed` go in the options. */
|
|
253
|
+
export function marketplaceSearch(keyword, city, { limit = 5, ...options } = {}) {
|
|
254
|
+
const item = { keyword, city, ...given(options) };
|
|
255
|
+
return run(MARKETPLACE, [item], { discoverBy: "keyword", limitPerInput: limit });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Listings from a Marketplace category URL, such as .../marketplace/category/vehicles. */
|
|
259
|
+
export function marketplaceCategory(urls, { limit = 5 } = {}) {
|
|
260
|
+
return run(MARKETPLACE, items(urls), { discoverBy: "url", limitPerInput: limit });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** Full records for Meta Ad Library ad URLs, .../ads/library/?id=... */
|
|
264
|
+
export function ads(urls) {
|
|
265
|
+
return run(AD_LIBRARY, items(urls));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Ads in the Meta Ad Library matching a keyword in one country.
|
|
270
|
+
*
|
|
271
|
+
* `ad_type` is validated against a fixed list: "All ads" is accepted, "all" is not.
|
|
272
|
+
*/
|
|
273
|
+
export function adsSearch(keyword, { country = "US", limit = 5, ad_type = "All ads" } = {}) {
|
|
274
|
+
const item = { keyword, country: country.toUpperCase(), ad_type };
|
|
275
|
+
return run(AD_LIBRARY, [item], { discoverBy: "keyword", limitPerInput: limit });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* When a discovery reaches `limitPerInput`, the crawls still running are
|
|
280
|
+
* cancelled and each comes back as a row with this error. That is the limit
|
|
281
|
+
* working, not a failure.
|
|
282
|
+
*/
|
|
283
|
+
export const CANCELLED = "Crawl aborted on job cancel";
|
|
284
|
+
|
|
285
|
+
/** Records, and the error messages of the rows that are not records. */
|
|
286
|
+
export function split(rows) {
|
|
287
|
+
return {
|
|
288
|
+
records: rows.filter((row) => !row.error),
|
|
289
|
+
errors: rows.filter((row) => row.error && row.error !== CANCELLED).map((row) => String(row.error)),
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* value parsed as a URL, when its host is domain or a subdomain of it.
|
|
295
|
+
* A substring test would let https://evil.com/facebook.com/x through; the host is
|
|
296
|
+
* what decides which site a URL names.
|
|
297
|
+
*/
|
|
298
|
+
function urlOn(value, domain) {
|
|
299
|
+
let url;
|
|
300
|
+
try {
|
|
301
|
+
url = new URL(value.includes("://") ? value : `https://${value}`);
|
|
302
|
+
} catch {
|
|
303
|
+
return null;
|
|
304
|
+
}
|
|
305
|
+
const host = url.hostname.toLowerCase();
|
|
306
|
+
return host === domain || host.endsWith(`.${domain}`) ? url : null;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** value without leading and trailing ch, without a backtracking regex. */
|
|
310
|
+
function trimChar(value, ch, { start = true, end = true } = {}) {
|
|
311
|
+
let from = 0;
|
|
312
|
+
let to = value.length;
|
|
313
|
+
while (start && from < to && value[from] === ch) from += 1;
|
|
314
|
+
while (end && to > from && value[to - 1] === ch) to -= 1;
|
|
315
|
+
return value.slice(from, to);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** new URL() percent-encodes the path; keep a page name as it was typed. */
|
|
319
|
+
function safeDecode(path) {
|
|
320
|
+
try {
|
|
321
|
+
return decodeURIComponent(path);
|
|
322
|
+
} catch {
|
|
323
|
+
return path;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Accept Meta, @Meta, facebook.com/Meta or a full URL. Reject anything else. */
|
|
328
|
+
export function pageUrl(page) {
|
|
329
|
+
const cleaned = String(page ?? "").trim();
|
|
330
|
+
if (trimChar(cleaned, "/").includes("/")) {
|
|
331
|
+
const url = urlOn(cleaned, "facebook.com");
|
|
332
|
+
const path = url ? trimChar(safeDecode(url.pathname), "/") : "";
|
|
333
|
+
if (!path) throw new Error(`${JSON.stringify(page)} is not a Facebook page`);
|
|
334
|
+
return `https://www.facebook.com/${path}${url.search}`;
|
|
335
|
+
}
|
|
336
|
+
const name = trimChar(trimChar(cleaned, "@", { end: false }), "/");
|
|
337
|
+
if (!/^[\p{L}\p{N}._-]+$/u.test(name)) throw new Error(`${JSON.stringify(page)} is not a Facebook page name`);
|
|
338
|
+
return `https://www.facebook.com/${name}`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** What happened to one page. */
|
|
342
|
+
export class Outcome {
|
|
343
|
+
constructor({ page, posts = [], error = null, note = "" }) {
|
|
344
|
+
this.page = page;
|
|
345
|
+
this.posts = posts;
|
|
346
|
+
this.error = error;
|
|
347
|
+
this.note = note;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
get ok() {
|
|
351
|
+
return this.error === null;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** One line a reader can understand without having read the source. */
|
|
355
|
+
line() {
|
|
356
|
+
if (!this.ok) return `failed ${this.page}: ${this.error}`;
|
|
357
|
+
const tail = this.note ? `, ${this.note}` : "";
|
|
358
|
+
return `got ${this.page}: ${this.posts.length} posts${tail}`;
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Fetch one page's recent posts. Never rejects for a bad page: a failure
|
|
364
|
+
* becomes an Outcome. A missing token is the exception, because it fails
|
|
365
|
+
* every page the same way.
|
|
366
|
+
*/
|
|
367
|
+
export async function scrapePage(page, { limit = 5 } = {}) {
|
|
368
|
+
let url;
|
|
369
|
+
try {
|
|
370
|
+
url = pageUrl(page);
|
|
371
|
+
} catch (error) {
|
|
372
|
+
return new Outcome({ page: String(page), error: error.message });
|
|
373
|
+
}
|
|
374
|
+
const outcome = new Outcome({ page: url.slice(url.lastIndexOf("facebook.com/") + "facebook.com/".length) });
|
|
375
|
+
let rows;
|
|
376
|
+
try {
|
|
377
|
+
rows = await pagePosts(url, { limit });
|
|
378
|
+
} catch (error) {
|
|
379
|
+
if (error instanceof TokenMissing) throw error;
|
|
380
|
+
// one bad page must not end the run
|
|
381
|
+
outcome.error = error instanceof ApiError ? error.message : `${error?.name ?? "Error"}: ${error?.message ?? error}`;
|
|
382
|
+
return outcome;
|
|
383
|
+
}
|
|
384
|
+
const { records, errors } = split(rows);
|
|
385
|
+
if (records.length) {
|
|
386
|
+
// Keep what was paid for. A partial run reports the rest as a note.
|
|
387
|
+
outcome.posts = records;
|
|
388
|
+
if (errors.length) outcome.note = `${errors.length} error rows: ${errors[0]}`;
|
|
389
|
+
} else if (errors.length) {
|
|
390
|
+
outcome.error = [...new Set(errors)].join("; ");
|
|
391
|
+
}
|
|
392
|
+
return outcome;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Run every page and return one Outcome each, in order. */
|
|
396
|
+
export async function scrape(pageNames, { limit = 5 } = {}) {
|
|
397
|
+
const outcomes = [];
|
|
398
|
+
for (const page of pageNames) outcomes.push(await scrapePage(page, { limit }));
|
|
399
|
+
return outcomes;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/** Write one JSON file: when it ran, and the posts found per page. */
|
|
403
|
+
export async function write(outcomes, path) {
|
|
404
|
+
const document = {
|
|
405
|
+
generated_at: new Date().toISOString(),
|
|
406
|
+
pages: outcomes.map((o) => ({ page: o.page, posts: o.posts })),
|
|
407
|
+
};
|
|
408
|
+
const target = resolve(path);
|
|
409
|
+
await mkdir(dirname(target), { recursive: true });
|
|
410
|
+
await writeFile(target, `${JSON.stringify(document, null, 2)}\n`, "utf8");
|
|
411
|
+
return target;
|
|
412
|
+
}
|