-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.js
More file actions
77 lines (65 loc) · 2.34 KB
/
scraper.js
File metadata and controls
77 lines (65 loc) · 2.34 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
require('dotenv').config();
const LinkedInProfileScraper = require('./LinkedInProfileScraper');
const path = require('path');
const fs = require('fs');
// Create profiles directory if it doesn't exist
const ensureProfilesDirectory = () => {
const profilesDir = path.join(__dirname, 'profiles');
if (!fs.existsSync(profilesDir)) {
fs.mkdirSync(profilesDir, { recursive: true });
}
return profilesDir;
};
// Improved function to scrape a LinkedIn profile
async function scrapeLinkedInProfile(profileUrl) {
if (!profileUrl || !profileUrl.includes('linkedin.com/in/')) {
throw new Error('Invalid LinkedIn profile URL');
}
// Create a new scraper instance with custom options
const scraper = new LinkedInProfileScraper({
headless: true, // Run in headless mode for production
slowMo: 200, // Slow down actions to reduce detection
timeout: 60000, // Longer timeout for reliability
debug: false // Disable debug for production
});
try {
// Setup the browser
console.log("Setting up browser...");
await scraper.setup();
// Check if we're logged in
console.log("Checking login status...");
await scraper.checkLogin(profileUrl);
// Scrape the profile
console.log(`Scraping profile: ${profileUrl}`);
const profileData = await scraper.scrapeProfile(profileUrl);
if (!profileData) {
throw new Error('Failed to retrieve profile data');
}
// Create a filename based on the LinkedIn username
const username = profileUrl.split('/in/')[1].replace(/\/$/, '').split('?')[0];
const profilesDir = ensureProfilesDirectory();
const outputPath = path.join(profilesDir, `${username}.json`);
// Save the data to a file
await scraper.saveProfileData(profileData, outputPath);
console.log(`Successfully scraped profile data for ${profileData.name || username}`);
return {
success: true,
data: profileData,
savedTo: outputPath
};
} catch (error) {
console.error(`Error during scraping: ${error.message}`);
return {
success: false,
error: error.message
};
} finally {
// Always close the browser to free resources
try {
await scraper.close();
} catch (e) {
console.error('Error closing browser:', e);
}
}
}
module.exports = { scrapeLinkedInProfile };