-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark-test.js
More file actions
339 lines (286 loc) · 11.1 KB
/
Copy pathbenchmark-test.js
File metadata and controls
339 lines (286 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// LinkedIn 数据获取性能基准测试
const axios = require('axios');
const cheerio = require('cheerio');
const LinkedInScraper = require('./linkedin-api-advanced');
class PerformanceBenchmark {
constructor() {
this.results = {
original: { times: [], errors: 0, success: 0 },
optimized: { times: [], errors: 0, success: 0 },
advanced: { times: [], errors: 0, success: 0 }
};
this.testCases = [
{ keyword: 'frontend', location: 'Worldwide' },
{ keyword: 'react', location: 'United States' },
{ keyword: 'python', location: 'Europe' }
];
}
// 原始简单版本 (你的初始代码)
async originalMethod(keyword, location) {
const url = `https://www.linkedin.com/jobs-guest/jobs/api/seeMoreJobPostings/search?keywords=${encodeURIComponent(keyword)}&location=${encodeURIComponent(location)}&start=0`;
const headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8'
};
const startTime = Date.now();
try {
const resp = await axios.get(url, { headers, timeout: 10000 });
const endTime = Date.now();
const $ = cheerio.load(resp.data);
const jobCount = $('li').filter((i, el) =>
$(el).find('div.base-card').attr('data-entity-urn')
).length;
return {
success: true,
time: endTime - startTime,
jobCount,
method: 'original'
};
} catch (error) {
return {
success: false,
time: Date.now() - startTime,
error: error.message,
method: 'original'
};
}
}
// 优化版本 (基于你的 job.js 改进)
async optimizedMethod(keyword, location) {
const client = axios.create({
timeout: 15000,
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.9',
'Accept-Encoding': 'gzip, deflate, br',
'Sec-Ch-Ua': '"Chromium";v="118", "Google Chrome";v="118"',
'Sec-Ch-Ua-Mobile': '?0',
'Sec-Ch-Ua-Platform': '"macOS"',
'Sec-Fetch-Dest': 'document',
'Sec-Fetch-Mode': 'navigate',
'Sec-Fetch-Site': 'none',
'Connection': 'keep-alive'
}
});
const url = `https://www.linkedin.com/jobs-guest/jobs/api/seeMoreJobPostings/search?keywords=${encodeURIComponent(keyword)}&location=${encodeURIComponent(location)}&start=0`;
const startTime = Date.now();
try {
// 添加随机延迟模拟人类行为
await this.delay(Math.random() * 1000 + 500);
const resp = await client.get(url);
const endTime = Date.now();
const $ = cheerio.load(resp.data);
const jobCount = $('li').filter((i, el) =>
$(el).find('div.base-card').attr('data-entity-urn')
).length;
return {
success: true,
time: endTime - startTime,
jobCount,
method: 'optimized'
};
} catch (error) {
return {
success: false,
time: Date.now() - startTime,
error: error.message,
method: 'optimized'
};
}
}
// 高级版本 (使用 LinkedInScraper 类)
async advancedMethod(keyword, location) {
const scraper = new LinkedInScraper({
maxRetries: 2,
retryDelay: 1000,
rateLimitDelay: { min: 500, max: 1500 }
});
const startTime = Date.now();
try {
const jobs = await scraper.searchJobs(keyword, location, 0);
const endTime = Date.now();
return {
success: true,
time: endTime - startTime,
jobCount: jobs.length,
method: 'advanced'
};
} catch (error) {
return {
success: false,
time: Date.now() - startTime,
error: error.message,
method: 'advanced'
};
}
}
delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async runSingleTest(method, keyword, location, testNumber) {
console.log(`🧪 测试 ${testNumber}: ${method} - ${keyword} @ ${location}`);
let result;
switch (method) {
case 'original':
result = await this.originalMethod(keyword, location);
break;
case 'optimized':
result = await this.optimizedMethod(keyword, location);
break;
case 'advanced':
result = await this.advancedMethod(keyword, location);
break;
}
// 记录结果
this.results[method].times.push(result.time);
if (result.success) {
this.results[method].success++;
console.log(` ✅ 成功: ${result.time}ms, 找到 ${result.jobCount} 个职位`);
} else {
this.results[method].errors++;
console.log(` ❌ 失败: ${result.time}ms, 错误: ${result.error}`);
}
return result;
}
async runBenchmark() {
console.log('🚀 开始 LinkedIn API 性能基准测试\n');
console.log(`测试用例: ${this.testCases.length} 个`);
console.log(`测试方法: original, optimized, advanced`);
console.log(`每个方法运行: ${this.testCases.length} 次\n`);
const methods = ['original', 'optimized', 'advanced'];
for (const method of methods) {
console.log(`\n📊 测试方法: ${method.toUpperCase()}`);
console.log('='.repeat(50));
for (let i = 0; i < this.testCases.length; i++) {
const testCase = this.testCases[i];
try {
await this.runSingleTest(method, testCase.keyword, testCase.location, i + 1);
// 测试间隔,避免被限制
if (i < this.testCases.length - 1) {
console.log(` ⏱️ 等待 3 秒...`);
await this.delay(3000);
}
} catch (error) {
console.error(` 💥 测试异常: ${error.message}`);
this.results[method].errors++;
}
}
// 方法间更长的等待时间
if (method !== methods[methods.length - 1]) {
console.log(`\n⏸️ 方法间等待 5 秒...\n`);
await this.delay(5000);
}
}
}
generateReport() {
console.log('\n\n📈 === 性能测试报告 ===');
console.log('='.repeat(60));
const methods = ['original', 'optimized', 'advanced'];
const reportData = [];
methods.forEach(method => {
const data = this.results[method];
const totalTests = data.times.length;
const successRate = ((data.success / totalTests) * 100).toFixed(1);
const avgTime = data.times.length > 0
? (data.times.reduce((a, b) => a + b, 0) / data.times.length).toFixed(0)
: 0;
const minTime = data.times.length > 0 ? Math.min(...data.times) : 0;
const maxTime = data.times.length > 0 ? Math.max(...data.times) : 0;
reportData.push({
method: method.toUpperCase(),
tests: totalTests,
success: data.success,
errors: data.errors,
successRate: successRate + '%',
avgTime: avgTime + 'ms',
minTime: minTime + 'ms',
maxTime: maxTime + 'ms'
});
});
// 表格输出
console.log('\\n📊 详细统计:');
console.table(reportData);
// 性能改进分析
console.log('\\n🔍 性能改进分析:');
if (reportData.length >= 3) {
const original = this.results.original;
const optimized = this.results.optimized;
const advanced = this.results.advanced;
const originalAvg = original.times.length > 0
? original.times.reduce((a, b) => a + b, 0) / original.times.length
: 0;
const optimizedAvg = optimized.times.length > 0
? optimized.times.reduce((a, b) => a + b, 0) / optimized.times.length
: 0;
const advancedAvg = advanced.times.length > 0
? advanced.times.reduce((a, b) => a + b, 0) / advanced.times.length
: 0;
if (originalAvg > 0) {
const optimizedImprovement = ((originalAvg - optimizedAvg) / originalAvg * 100).toFixed(1);
const advancedImprovement = ((originalAvg - advancedAvg) / originalAvg * 100).toFixed(1);
console.log(`• 优化版本比原始版本快: ${optimizedImprovement}%`);
console.log(`• 高级版本比原始版本快: ${advancedImprovement}%`);
}
const originalSuccess = (original.success / original.times.length * 100);
const optimizedSuccess = (optimized.success / optimized.times.length * 100);
const advancedSuccess = (advanced.success / advanced.times.length * 100);
console.log(`• 成功率改进: ${originalSuccess.toFixed(1)}% → ${optimizedSuccess.toFixed(1)}% → ${advancedSuccess.toFixed(1)}%`);
}
// 推荐方案
console.log('\\n💡 推荐方案:');
const bestMethod = reportData.reduce((best, current) => {
const currentScore = parseFloat(current.successRate) * 0.7 +
(10000 / parseFloat(current.avgTime)) * 0.3;
const bestScore = parseFloat(best.successRate) * 0.7 +
(10000 / parseFloat(best.avgTime)) * 0.3;
return currentScore > bestScore ? current : best;
});
console.log(`推荐使用: ${bestMethod.method} 方案`);
console.log(`理由: 成功率 ${bestMethod.successRate}, 平均响应时间 ${bestMethod.avgTime}`);
// 使用建议
console.log('\\n🛠️ 集成建议:');
console.log('1. 开发环境: 使用 OPTIMIZED 方案(快速测试)');
console.log('2. 生产环境: 使用 ADVANCED 方案(稳定可靠)');
console.log('3. 大批量抓取: 考虑混合 ADVANCED + Playwright 备用');
console.log('4. 速率限制: 建议间隔 1-3 秒,避免IP被封');
}
async runQuickTest() {
console.log('🔥 快速测试模式 - 每种方法测试一次\n');
const testCase = { keyword: 'frontend', location: 'Worldwide' };
const methods = ['original', 'optimized', 'advanced'];
for (const method of methods) {
await this.runSingleTest(method, testCase.keyword, testCase.location, 1);
if (method !== methods[methods.length - 1]) {
await this.delay(2000);
}
}
this.generateReport();
}
}
// 主函数
async function main() {
const benchmark = new PerformanceBenchmark();
const mode = process.argv[2] || 'quick';
try {
if (mode === 'full') {
console.log('🏁 完整基准测试模式 (需要 ~3 分钟)');
await benchmark.runBenchmark();
} else {
console.log('⚡ 快速测试模式 (需要 ~30 秒)');
await benchmark.runQuickTest();
}
benchmark.generateReport();
} catch (error) {
console.error('❌ 基准测试失败:', error.message);
}
}
if (require.main === module) {
console.log('🧪 LinkedIn API 性能基准测试工具');
console.log('用法:');
console.log(' node benchmark-test.js quick # 快速测试 (默认)');
console.log(' node benchmark-test.js full # 完整测试');
console.log('');
main().catch(console.error);
}
module.exports = PerformanceBenchmark;