Skip to content

Commit 581cc77

Browse files
author
gongzhenxing
committed
Set cookies in advance and modify code style
1 parent 247b87b commit 581cc77

File tree

2 files changed

+22
-20
lines changed

2 files changed

+22
-20
lines changed

src/config.ts

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,16 @@ export const configSchema = z.object({
3939
cookie: z
4040
.union([
4141
z.object({
42-
name: z.string(),
43-
value: z.string(),
42+
name: z.string(),
43+
value: z.string(),
4444
}),
45-
z.array(z.object({
46-
name: z.string(),
47-
value: z.string(),
48-
})),
49-
])
45+
z.array(
46+
z.object({
47+
name: z.string(),
48+
value: z.string(),
49+
}),
50+
),
51+
])
5052
.optional(),
5153
/** Optional function to run for each page found */
5254
onVisitPage: z

src/core.ts

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -55,18 +55,6 @@ export async function crawl(config: Config) {
5555
const crawler = new PlaywrightCrawler({
5656
// Use the requestHandler to process each of the crawled pages.
5757
async requestHandler({ request, page, enqueueLinks, log, pushData }) {
58-
if (config.cookie) {
59-
const cookies = (Array.isArray(config.cookie) ? config.cookie : [config.cookie])
60-
.map((cookie)=>{
61-
return {
62-
name:cookie.name,
63-
value:cookie.value,
64-
url:request.loadedUrl
65-
}
66-
});
67-
await page.context().addCookies(cookies);
68-
}
69-
7058
const title = await page.title();
7159
pageCounter++;
7260
log.info(
@@ -110,12 +98,24 @@ export async function crawl(config: Config) {
11098
// headless: false,
11199
preNavigationHooks: [
112100
// Abort requests for certain resource types
113-
async ({ page, log }) => {
101+
async ({ request, page, log }) => {
114102
// If there are no resource exclusions, return
115103
const RESOURCE_EXCLUSTIONS = config.resourceExclusions ?? [];
116104
if (RESOURCE_EXCLUSTIONS.length === 0) {
117105
return;
118106
}
107+
if (config.cookie) {
108+
const cookies = (
109+
Array.isArray(config.cookie) ? config.cookie : [config.cookie]
110+
).map((cookie) => {
111+
return {
112+
name: cookie.name,
113+
value: cookie.value,
114+
url: request.loadedUrl,
115+
};
116+
});
117+
await page.context().addCookies(cookies);
118+
}
119119
await page.route(`**\/*.{${RESOURCE_EXCLUSTIONS.join()}}`, (route) =>
120120
route.abort("aborted"),
121121
);

0 commit comments

Comments
 (0)