|
| 1 | +import { sitemap, smartScraper } from 'scrapegraph-js'; |
| 2 | +import 'dotenv/config'; |
| 3 | + |
| 4 | +/** |
| 5 | + * Advanced Example: Extract sitemap and scrape selected URLs |
| 6 | + * |
| 7 | + * This example demonstrates how to combine the sitemap endpoint |
| 8 | + * with smartScraper to extract structured data from multiple pages. |
| 9 | + */ |
| 10 | + |
| 11 | +const apiKey = process.env.SGAI_APIKEY; |
| 12 | + |
| 13 | +// Configuration |
| 14 | +const websiteUrl = 'https://scrapegraphai.com/'; |
| 15 | +const maxPagesToScrape = 3; // Limit number of pages to scrape |
| 16 | +const userPrompt = 'Extract the page title and main heading'; |
| 17 | + |
| 18 | +console.log('🗺️ Step 1: Extracting sitemap from:', websiteUrl); |
| 19 | +console.log('⏳ Please wait...\n'); |
| 20 | + |
| 21 | +try { |
| 22 | + // Step 1: Get all URLs from sitemap |
| 23 | + const sitemapResponse = await sitemap(apiKey, websiteUrl); |
| 24 | + |
| 25 | + console.log('✅ Sitemap extracted successfully!'); |
| 26 | + console.log(`📊 Total URLs found: ${sitemapResponse.urls.length}\n`); |
| 27 | + |
| 28 | + // Step 2: Filter URLs (example: only blog posts) |
| 29 | + const filteredUrls = sitemapResponse.urls |
| 30 | + .filter(url => url.includes('/blog/') || url.includes('/post/')) |
| 31 | + .slice(0, maxPagesToScrape); |
| 32 | + |
| 33 | + if (filteredUrls.length === 0) { |
| 34 | + console.log('ℹ️ No blog URLs found, using first 3 URLs instead'); |
| 35 | + filteredUrls.push(...sitemapResponse.urls.slice(0, maxPagesToScrape)); |
| 36 | + } |
| 37 | + |
| 38 | + console.log(`🎯 Selected ${filteredUrls.length} URLs to scrape:`); |
| 39 | + filteredUrls.forEach((url, index) => { |
| 40 | + console.log(` ${index + 1}. ${url}`); |
| 41 | + }); |
| 42 | + |
| 43 | + // Step 3: Scrape each selected URL |
| 44 | + console.log('\n🤖 Step 2: Scraping selected URLs...\n'); |
| 45 | + |
| 46 | + const results = []; |
| 47 | + |
| 48 | + for (let i = 0; i < filteredUrls.length; i++) { |
| 49 | + const url = filteredUrls[i]; |
| 50 | + console.log(`📄 Scraping (${i + 1}/${filteredUrls.length}): ${url}`); |
| 51 | + |
| 52 | + try { |
| 53 | + const scrapeResponse = await smartScraper( |
| 54 | + apiKey, |
| 55 | + url, |
| 56 | + userPrompt |
| 57 | + ); |
| 58 | + |
| 59 | + results.push({ |
| 60 | + url: url, |
| 61 | + data: scrapeResponse.result, |
| 62 | + status: 'success' |
| 63 | + }); |
| 64 | + |
| 65 | + console.log(' ✅ Success'); |
| 66 | + |
| 67 | + // Add a small delay between requests to avoid rate limiting |
| 68 | + if (i < filteredUrls.length - 1) { |
| 69 | + await new Promise(resolve => setTimeout(resolve, 1000)); |
| 70 | + } |
| 71 | + |
| 72 | + } catch (error) { |
| 73 | + console.log(` ❌ Failed: ${error.message}`); |
| 74 | + results.push({ |
| 75 | + url: url, |
| 76 | + error: error.message, |
| 77 | + status: 'failed' |
| 78 | + }); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + // Step 4: Display results |
| 83 | + console.log('\n📊 Scraping Results:\n'); |
| 84 | + results.forEach((result, index) => { |
| 85 | + console.log(`${index + 1}. ${result.url}`); |
| 86 | + if (result.status === 'success') { |
| 87 | + console.log(' Status: ✅ Success'); |
| 88 | + console.log(' Data:', JSON.stringify(result.data, null, 2)); |
| 89 | + } else { |
| 90 | + console.log(' Status: ❌ Failed'); |
| 91 | + console.log(' Error:', result.error); |
| 92 | + } |
| 93 | + console.log(''); |
| 94 | + }); |
| 95 | + |
| 96 | + // Summary |
| 97 | + const successCount = results.filter(r => r.status === 'success').length; |
| 98 | + console.log('📈 Summary:'); |
| 99 | + console.log(` ✅ Successful: ${successCount}`); |
| 100 | + console.log(` ❌ Failed: ${results.length - successCount}`); |
| 101 | + console.log(` 📊 Total: ${results.length}`); |
| 102 | + |
| 103 | +} catch (error) { |
| 104 | + console.error('❌ Error:', error.message); |
| 105 | + process.exit(1); |
| 106 | +} |
0 commit comments