在SvelteKit中使用LinkedIn爬虫库遇util.promisify兼容问题求助
解决SvelteKit中使用LinkedIn Profile Scraper的"util模块外部化"错误
这个错误的核心原因是你使用的@n-h-n/linkedin-profile-scraper是为Node.js服务器环境设计的库,它依赖Node.js内置的util模块(包括util.promisify方法),但你的代码直接在SvelteKit客户端(浏览器环境)中运行,浏览器没有Node.js的内置模块,因此出现兼容性报错。
必须将爬虫逻辑移到SvelteKit的服务器端执行,客户端仅通过API调用获取爬取结果,具体步骤如下:
1. 创建服务器端API路由
在SvelteKit项目中创建一个API路由文件,专门处理爬虫逻辑:
// src/routes/api/scrape-linkedin/+server.js import { LinkedInProfileScraper } from '@n-h-n/linkedin-profile-scraper'; import { error } from '@sveltejs/kit'; export async function POST({ request, locals }) { // 从请求体获取目标LinkedIn个人主页URL const { profileUrl } = await request.json(); // 从服务器端locals获取session令牌(需确保session已配置到locals) const token = locals.session?.provider_token; if (!token) throw error(401, '未找到会话令牌'); if (!profileUrl) throw error(400, '缺少目标个人主页URL'); try { const scraper = new LinkedInProfileScraper({ sessionCookieValue: token, keepAlive: false }); await scraper.setup(); const result = await scraper.run(profileUrl); return new Response(JSON.stringify(result), { headers: { 'Content-Type': 'application/json' } }); } catch (err) { throw error(500, `爬取失败:${err.message}`); } }
2. 修改客户端组件代码
将原客户端中的爬虫逻辑替换为API调用,仅在浏览器中发起请求获取结果:
<script> import { onMount } from 'svelte'; import { session } from '$app/stores'; onMount(async () => { const currentSession = await session; const token = currentSession?.provider_token; if (!token) { console.error('无可用会话令牌'); return; } try { const response = await fetch('/api/scrape-linkedin', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ profileUrl: 'https://www.linkedin.com/in/jvandenaardweg/' }) }); if (!response.ok) throw new Error(`请求失败:${response.status}`); const result = await response.json(); console.log('爬取结果:', result); } catch (err) { console.error('处理错误:', err); } }); </script>
3. 关键配置注意事项
- 确保你的SvelteKit使用支持服务器端运行的适配器(如
@sveltejs/adapter-node),不能使用静态适配器(adapter-static),因为静态环境没有Node.js运行时。 - 确认SvelteKit的session已正确配置,服务器端
locals.session能获取到有效的LinkedIn会话令牌。 - 遵守LinkedIn服务条款,频繁爬取可能导致账号受限,建议控制请求频率。
内容的提问来源于stack exchange,提问作者equi
相关产品推荐
相关产品推荐

