|
| 1 | +/** |
| 2 | + * Advanced SearchScraper Markdown Example with Async Polling |
| 3 | + * |
| 4 | + * This example demonstrates using the SearchScraper API in markdown mode |
| 5 | + * with async request handling and result polling. |
| 6 | + * |
| 7 | + * Features demonstrated: |
| 8 | + * - Async search and scrape with markdown output |
| 9 | + * - Polling for async results with timeout handling |
| 10 | + * - Error handling with async operations |
| 11 | + * - Cost-effective: Only 2 credits per page (vs 10 credits for AI extraction) |
| 12 | + */ |
| 13 | + |
| 14 | +import { searchScraper, getSearchScraperRequest } from 'scrapegraph-js'; |
| 15 | +import 'dotenv/config'; |
| 16 | + |
| 17 | +const apiKey = process.env.SGAI_APIKEY; |
| 18 | + |
| 19 | +/** |
| 20 | + * Poll for completion of an async SearchScraper request. |
| 21 | + * |
| 22 | + * @param {string} requestId - The request ID to poll for |
| 23 | + * @param {number} maxWaitTime - Maximum time to wait in seconds |
| 24 | + * @returns {Promise<Object|null>} The completed response or null if timeout |
| 25 | + */ |
| 26 | +async function waitForCompletion(requestId, maxWaitTime = 60) { |
| 27 | + const startTime = Date.now(); |
| 28 | + |
| 29 | + while (Date.now() - startTime < maxWaitTime * 1000) { |
| 30 | + try { |
| 31 | + const result = await getSearchScraperRequest(apiKey, requestId); |
| 32 | + |
| 33 | + if (result.status === 'completed') { |
| 34 | + return result; |
| 35 | + } else if (result.status === 'failed') { |
| 36 | + console.error(`❌ Request failed: ${result.error || 'Unknown error'}`); |
| 37 | + return null; |
| 38 | + } else { |
| 39 | + console.log(`⏳ Status: ${result.status || 'processing'}... waiting 5 seconds`); |
| 40 | + await new Promise(resolve => setTimeout(resolve, 5000)); |
| 41 | + } |
| 42 | + |
| 43 | + } catch (error) { |
| 44 | + console.warn(`⚠️ Error polling for results: ${error.message}`); |
| 45 | + await new Promise(resolve => setTimeout(resolve, 5000)); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + console.log('⏰ Timeout waiting for completion'); |
| 50 | + return null; |
| 51 | +} |
| 52 | + |
| 53 | +async function advancedSearchScraperMarkdownExample() { |
| 54 | + console.log('🔍 Advanced SearchScraper Markdown Example with Async Polling'); |
| 55 | + console.log('='.repeat(60)); |
| 56 | + |
| 57 | + // Configuration |
| 58 | + const userPrompt = 'Latest developments in artificial intelligence'; |
| 59 | + const numResults = 3; |
| 60 | + |
| 61 | + console.log(`📝 Query: ${userPrompt}`); |
| 62 | + console.log(`📊 Results: ${numResults} websites`); |
| 63 | + console.log('🔧 Mode: Markdown conversion'); |
| 64 | + console.log('💰 Cost: 2 credits per page (vs 10 for AI extraction)'); |
| 65 | + |
| 66 | + try { |
| 67 | + // Send a searchscraper request in markdown mode |
| 68 | + const response = await searchScraper( |
| 69 | + apiKey, |
| 70 | + userPrompt, |
| 71 | + numResults, |
| 72 | + null, // schema |
| 73 | + null, // userAgent |
| 74 | + { |
| 75 | + extractionMode: false, // false = markdown mode, true = AI extraction mode |
| 76 | + } |
| 77 | + ); |
| 78 | + |
| 79 | + console.log('\n✅ SearchScraper request submitted successfully!'); |
| 80 | + console.log(`📄 Request ID: ${response.request_id || 'N/A'}`); |
| 81 | + |
| 82 | + // Check if this is an async request that needs polling |
| 83 | + if (response.request_id && !response.status) { |
| 84 | + console.log('⏳ Waiting for async processing to complete...'); |
| 85 | + |
| 86 | + // Poll for completion |
| 87 | + const finalResult = await waitForCompletion(response.request_id); |
| 88 | + |
| 89 | + if (finalResult) { |
| 90 | + // Update response with final results |
| 91 | + Object.assign(response, finalResult); |
| 92 | + } else { |
| 93 | + console.error('❌ Failed to get completed results'); |
| 94 | + return false; |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + // Display results |
| 99 | + if (response.status === 'completed') { |
| 100 | + console.log('\n🎉 SearchScraper markdown completed successfully!'); |
| 101 | + |
| 102 | + // Display markdown content (first 500 chars) |
| 103 | + if (response.markdown_content) { |
| 104 | + const markdownContent = response.markdown_content; |
| 105 | + console.log('\n📝 Markdown Content Preview:'); |
| 106 | + console.log(markdownContent.length > 500 |
| 107 | + ? markdownContent.substring(0, 500) + '...' |
| 108 | + : markdownContent |
| 109 | + ); |
| 110 | + } else { |
| 111 | + console.log('⚠️ No markdown content returned'); |
| 112 | + } |
| 113 | + |
| 114 | + // Display reference URLs |
| 115 | + if (response.reference_urls && response.reference_urls.length > 0) { |
| 116 | + console.log(`\n🔗 References: ${response.reference_urls.length}`); |
| 117 | + console.log('\n🔗 Reference URLs:'); |
| 118 | + response.reference_urls.forEach((url, index) => { |
| 119 | + console.log(` ${index + 1}. ${url}`); |
| 120 | + }); |
| 121 | + } else { |
| 122 | + console.log('⚠️ No reference URLs returned'); |
| 123 | + } |
| 124 | + |
| 125 | + return true; |
| 126 | + } else { |
| 127 | + console.error(`❌ Request not completed. Status: ${response.status || 'unknown'}`); |
| 128 | + return false; |
| 129 | + } |
| 130 | + |
| 131 | + } catch (error) { |
| 132 | + console.error(`❌ Error: ${error.message}`); |
| 133 | + return false; |
| 134 | + } |
| 135 | +} |
| 136 | + |
| 137 | +// Run the example |
| 138 | +try { |
| 139 | + const success = await advancedSearchScraperMarkdownExample(); |
| 140 | + process.exit(success ? 0 : 1); |
| 141 | +} catch (error) { |
| 142 | + console.error('❌ Unexpected error:', error.message); |
| 143 | + process.exit(1); |
| 144 | +} |
0 commit comments