1import { Actor } from 'apify';
2import { PlaywrightCrawler } from 'crawlee';
3import { URL } from 'url';
4
5
6await Actor.init();
7
8const input = await Actor.getInput();
9const urls = Array.isArray(input.startUrls)
10 ? input.startUrls.map(src => src.url)
11 : [];
12const results = [];
13
14const crawler = new PlaywrightCrawler({
15 launchContext: { launchOptions: { headless: true } },
16 maxRequestRetries: 0,
17 requestHandler: async ({ page, request, log }) => {
18 const url = request.url;
19 if (!/^https?:\/\/(www\.)?kwai\.com\//.test(url)) {
20 const err = { url, error: 'Invalid kwai.com URL' };
21 results.push(err);
22 const keyErr = `profile-error-${Buffer.from(url).toString('base64')}`;
23 await Actor.setValue(keyErr, JSON.stringify(err), { contentType: 'application/json' });
24 return;
25 }
26 log.info(`Opening ${url}`);
27
28 let navCount = 0;
29 await page.route('**', route => {
30 const req = route.request();
31 if (req.isNavigationRequest() && navCount > 0) return route.abort();
32 return route.continue();
33 });
34 page.on('framenavigated', frame => {
35 if (frame === page.mainFrame()) navCount++;
36 });
37
38 await page.goto(url, { waitUntil: 'commit', timeout: 60000 });
39 await page.evaluate(() => { window.location.reload = () => { }; history.pushState = () => { }; });
40
41 const start = Date.now();
42 let profileData = null;
43 while (Date.now() - start < 60000) {
44 try {
45 const handle = await page.$('#ItemList');
46 if (handle) {
47 const text = await handle.textContent();
48 const parsed = JSON.parse(text);
49 const mainEntity = parsed.mainEntityOfPage?.['@id'] || url;
50 const items = Array.isArray(parsed.itemListElement) ? parsed.itemListElement : [];
51 const totalVideos = items.length;
52 const person = items[0]?.creator?.mainEntity || {};
53
54 profileData = {
55 url,
56 profilePage: mainEntity,
57 identifier: person.identifier || null,
58 username: person.alternateName || null,
59 displayName: person.name || null,
60 biography: person.description || null,
61 avatar: person.image || null,
62 followersCount: person.interactionStatistic?.find(s =>
63 s.interactionType?.['@type']?.includes('FollowAction')
64 )?.userInteractionCount || 0,
65 likesCount: person.interactionStatistic?.find(s =>
66 s.interactionType?.['@type']?.includes('LikeAction')
67 )?.userInteractionCount || 0,
68 postsCount: person.agentInteractionStatistic?.userInteractionCount || 0,
69 sameAs: person.sameAs || [],
70 totalVideos,
71 };
72 break;
73 }
74 } catch {
75
76 }
77 await page.waitForTimeout(100);
78 }
79
80 if (profileData) {
81 results.push(profileData);
82 const key = profileData.identifier
83 ? `profile-${profileData.identifier}`
84 : `profile-${Buffer.from(profileData.url).toString('base64')}`;
85 await Actor.setValue(key, JSON.stringify(profileData), { contentType: 'application/json' });
86 } else {
87 const err = { url, error: 'Timeout fetching profile data' };
88 results.push(err);
89 const keyErr = `profile-error-${Buffer.from(url).toString('base64')}`;
90 await Actor.setValue(keyErr, JSON.stringify(err), { contentType: 'application/json' });
91 }
92 },
93 failedRequestHandler: async ({ request, error, log }) => {
94 log.error(`Request ${request.url} failed: ${error.message}`);
95 const err = { url: request.url, error: error.message };
96 results.push(err);
97 const keyErr = `profile-error-${Buffer.from(request.url).toString('base64')}`;
98 await Actor.setValue(keyErr, JSON.stringify(err), { contentType: 'application/json' });
99 },
100});
101
102
103await crawler.run(urls);
104
105
106await Actor.pushData(results);
107
108
109await Actor.exit();