-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathcookies_integration_example.js
More file actions
261 lines (220 loc) · 7.68 KB
/
Copy pathcookies_integration_example.js
File metadata and controls
261 lines (220 loc) · 7.68 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
/**
* Comprehensive example demonstrating cookies integration for web scraping.
*
* This example shows various real-world scenarios where cookies are essential:
* 1. E-commerce site scraping with authentication
* 2. Social media scraping with session cookies
* 3. Banking/financial site scraping with secure cookies
* 4. News site scraping with user preferences
* 5. API endpoint scraping with authentication tokens
*
* Requirements:
* - Node.js 16+
* - scrapegraph-js
* - A .env file with your SGAI_APIKEY
*
* Example .env file:
* SGAI_APIKEY=your_api_key_here
*/
import { smartScraper } from 'scrapegraph-js';
import { z } from 'zod';
import 'dotenv/config';
// Define data schemas for different scenarios
const ProductInfoSchema = z.object({
name: z.string().describe('Product name'),
price: z.string().describe('Product price'),
availability: z.string().describe('Product availability status'),
rating: z.string().optional().describe('Product rating')
});
const SocialMediaPostSchema = z.object({
author: z.string().describe('Post author'),
content: z.string().describe('Post content'),
likes: z.string().optional().describe('Number of likes'),
comments: z.string().optional().describe('Number of comments'),
timestamp: z.string().optional().describe('Post timestamp')
});
const NewsArticleSchema = z.object({
title: z.string().describe('Article title'),
summary: z.string().describe('Article summary'),
author: z.string().optional().describe('Article author'),
publish_date: z.string().optional().describe('Publish date')
});
const BankTransactionSchema = z.object({
date: z.string().describe('Transaction date'),
description: z.string().describe('Transaction description'),
amount: z.string().describe('Transaction amount'),
type: z.string().describe('Transaction type (credit/debit)')
});
async function scrapeEcommerceWithAuth() {
console.log('='.repeat(60));
console.log('E-COMMERCE SITE SCRAPING WITH AUTHENTICATION');
console.log('='.repeat(60));
// Example cookies for an e-commerce site
const cookies = {
session_id: 'abc123def456',
user_id: 'user789',
cart_id: 'cart101112',
preferences: 'dark_mode,usd',
auth_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
};
const websiteUrl = 'https://example-ecommerce.com/products';
const userPrompt = 'Extract product information including name, price, availability, and rating';
try {
const response = await smartScraper(
process.env.SGAI_APIKEY,
websiteUrl,
userPrompt,
ProductInfoSchema,
5, // numberOfScrolls - Scroll to load more products
null, // totalPages
cookies
);
console.log('✅ E-commerce scraping completed successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Error in e-commerce scraping: ${error.message}`);
}
}
async function scrapeSocialMediaWithSession() {
console.log('\n' + '='.repeat(60));
console.log('SOCIAL MEDIA SCRAPING WITH SESSION COOKIES');
console.log('='.repeat(60));
// Example cookies for a social media site
const cookies = {
session_token: 'xyz789abc123',
user_session: 'def456ghi789',
csrf_token: 'jkl012mno345',
remember_me: 'true',
language: 'en_US'
};
const websiteUrl = 'https://example-social.com/feed';
const userPrompt = 'Extract posts from the feed including author, content, likes, and comments';
try {
const response = await smartScraper(
process.env.SGAI_APIKEY,
websiteUrl,
userPrompt,
SocialMediaPostSchema,
10, // numberOfScrolls - Scroll to load more posts
null, // totalPages
cookies
);
console.log('✅ Social media scraping completed successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Error in social media scraping: ${error.message}`);
}
}
async function scrapeNewsWithPreferences() {
console.log('\n' + '='.repeat(60));
console.log('NEWS SITE SCRAPING WITH USER PREFERENCES');
console.log('='.repeat(60));
// Example cookies for a news site
const cookies = {
user_preferences: 'technology,science,ai',
reading_level: 'advanced',
region: 'US',
subscription_tier: 'premium',
theme: 'dark'
};
const websiteUrl = 'https://example-news.com/technology';
const userPrompt = 'Extract news articles including title, summary, author, and publish date';
try {
const response = await smartScraper(
process.env.SGAI_APIKEY,
websiteUrl,
userPrompt,
NewsArticleSchema,
null, // numberOfScrolls
3, // totalPages - Scrape multiple pages
cookies
);
console.log('✅ News scraping completed successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Error in news scraping: ${error.message}`);
}
}
async function scrapeBankingWithSecureCookies() {
console.log('\n' + '='.repeat(60));
console.log('BANKING SITE SCRAPING WITH SECURE COOKIES');
console.log('='.repeat(60));
// Example secure cookies for a banking site
const cookies = {
secure_session: 'pqr678stu901',
auth_token: 'vwx234yz567',
mfa_verified: 'true',
device_id: 'device_abc123',
last_activity: '2024-01-15T10:30:00Z'
};
const websiteUrl = 'https://example-bank.com/transactions';
const userPrompt = 'Extract recent transactions including date, description, amount, and type';
try {
const response = await smartScraper(
process.env.SGAI_APIKEY,
websiteUrl,
userPrompt,
BankTransactionSchema,
null, // numberOfScrolls
5, // totalPages - Scrape multiple pages of transactions
cookies
);
console.log('✅ Banking scraping completed successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Error in banking scraping: ${error.message}`);
}
}
async function scrapeApiWithAuthTokens() {
console.log('\n' + '='.repeat(60));
console.log('API ENDPOINT SCRAPING WITH AUTH TOKENS');
console.log('='.repeat(60));
// Example API authentication cookies
const cookies = {
api_token: 'api_abc123def456',
client_id: 'client_789',
access_token: 'access_xyz789',
refresh_token: 'refresh_abc123',
scope: 'read:all'
};
const websiteUrl = 'https://api.example.com/data';
const userPrompt = 'Extract data from the API response';
try {
const response = await smartScraper(
process.env.SGAI_APIKEY,
websiteUrl,
userPrompt,
null, // No schema for generic API response
null, // numberOfScrolls
null, // totalPages
cookies
);
console.log('✅ API scraping completed successfully');
console.log(JSON.stringify(response, null, 2));
} catch (error) {
console.error(`❌ Error in API scraping: ${error.message}`);
}
}
async function main() {
const apiKey = process.env.SGAI_APIKEY;
// Check if API key is available
if (!apiKey) {
console.error('Error: SGAI_APIKEY not found in .env file');
console.log('Please create a .env file with your API key:');
console.log('SGAI_APIKEY=your_api_key_here');
return;
}
console.log('🍪 COOKIES INTEGRATION EXAMPLES');
console.log('This demonstrates various real-world scenarios where cookies are essential for web scraping.');
// Run all examples
await scrapeEcommerceWithAuth();
await scrapeSocialMediaWithSession();
await scrapeNewsWithPreferences();
await scrapeBankingWithSecureCookies();
await scrapeApiWithAuthTokens();
console.log('\n' + '='.repeat(60));
console.log('✅ All examples completed!');
console.log('='.repeat(60));
}
// Run the example
main().catch(console.error);