|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import json |
| 4 | +from dotenv import load_dotenv |
| 5 | +from scrapegraphai.docloaders.chromium import ChromiumLoader # Import your ChromiumLoader class |
| 6 | +from scrapegraphai.graphs import SmartScraperGraph |
| 7 | +from scrapegraphai.utils import prettify_exec_info |
| 8 | +from aiohttp import ClientError |
| 9 | + |
| 10 | +# Load environment variables for API keys |
| 11 | +load_dotenv() |
| 12 | + |
| 13 | +# ************************************************ |
| 14 | +# Define function to analyze content with ScrapegraphAI |
| 15 | +# ************************************************ |
| 16 | +async def analyze_content_with_scrapegraph(content: str): |
| 17 | + """ |
| 18 | + Analyze scraped content using ScrapegraphAI. |
| 19 | + |
| 20 | + Args: |
| 21 | + content (str): The scraped HTML or text content. |
| 22 | +
|
| 23 | + Returns: |
| 24 | + dict: The result from ScrapegraphAI analysis. |
| 25 | + """ |
| 26 | + try: |
| 27 | + # Initialize ScrapegraphAI SmartScraperGraph |
| 28 | + smart_scraper = SmartScraperGraph( |
| 29 | + prompt="Summarize the main content of this webpage and extract any contact information.", |
| 30 | + source=content, # Pass the content directly |
| 31 | + config={ |
| 32 | + "llm": { |
| 33 | + "api_key": os.getenv("OPENAI_API_KEY"), |
| 34 | + "model": "openai/gpt-4o", |
| 35 | + }, |
| 36 | + "verbose": True |
| 37 | + } |
| 38 | + ) |
| 39 | + result = smart_scraper.run() |
| 40 | + return result |
| 41 | + except Exception as e: |
| 42 | + print(f"❌ ScrapegraphAI analysis failed: {e}") |
| 43 | + return {"error": str(e)} |
| 44 | + |
| 45 | +# ************************************************ |
| 46 | +# Test scraper and ScrapegraphAI pipeline |
| 47 | +# ************************************************ |
| 48 | +async def test_scraper_with_analysis(scraper: ChromiumLoader, urls: list): |
| 49 | + """ |
| 50 | + Test scraper for the given backend and URLs, then analyze content with ScrapegraphAI. |
| 51 | +
|
| 52 | + Args: |
| 53 | + scraper (ChromiumLoader): The ChromiumLoader instance. |
| 54 | + urls (list): A list of URLs to scrape. |
| 55 | + """ |
| 56 | + for url in urls: |
| 57 | + try: |
| 58 | + print(f"\n🔎 Scraping: {url} using {scraper.backend}...") |
| 59 | + result = await scraper.scrape(url) |
| 60 | + |
| 61 | + if "Error" in result or not result.strip(): |
| 62 | + print(f"❌ Failed to scrape {url}: {result}") |
| 63 | + else: |
| 64 | + print(f"✅ Successfully scraped {url}. Content (first 200 chars): {result[:200]}") |
| 65 | + |
| 66 | + # Pass scraped content to ScrapegraphAI for analysis |
| 67 | + print("🤖 Analyzing content with ScrapegraphAI...") |
| 68 | + analysis_result = await analyze_content_with_scrapegraph(result) |
| 69 | + print("📝 Analysis Result:") |
| 70 | + print(json.dumps(analysis_result, indent=4)) |
| 71 | + |
| 72 | + except ClientError as ce: |
| 73 | + print(f"❌ Network error while scraping {url}: {ce}") |
| 74 | + except Exception as e: |
| 75 | + print(f"❌ Unexpected error while scraping {url}: {e}") |
| 76 | + |
| 77 | +# ************************************************ |
| 78 | +# Main Execution |
| 79 | +# ************************************************ |
| 80 | +async def main(): |
| 81 | + urls_to_scrape = [ |
| 82 | + "https://example.com", |
| 83 | + "https://www.python.org", |
| 84 | + "https://invalid-url.test" |
| 85 | + ] |
| 86 | + |
| 87 | + # Test with Playwright backend |
| 88 | + print("\n--- Testing Playwright Backend ---") |
| 89 | + try: |
| 90 | + scraper_playwright_chromium = ChromiumLoader(urls=urls_to_scrape, backend="playwright", headless=True, browser_name = "chromium") |
| 91 | + await test_scraper_with_analysis(scraper_playwright_chromium, urls_to_scrape) |
| 92 | + |
| 93 | + scraper_playwright_firefox = ChromiumLoader(urls=urls_to_scrape, backend="playwright", headless=True, browser_name = "firefox") |
| 94 | + await test_scraper_with_analysis(scraper_playwright_firefox, urls_to_scrape) |
| 95 | + except ImportError as ie: |
| 96 | + print(f"❌ Playwright ImportError: {ie}") |
| 97 | + except Exception as e: |
| 98 | + print(f"❌ Error initializing Playwright ChromiumLoader: {e}") |
| 99 | + |
| 100 | + # Test with Selenium backend |
| 101 | + print("\n--- Testing Selenium Backend ---") |
| 102 | + try: |
| 103 | + scraper_selenium_chromium = ChromiumLoader(urls=urls_to_scrape, backend="selenium", headless=True, browser_name = "chromium") |
| 104 | + await test_scraper_with_analysis(scraper_selenium_chromium, urls_to_scrape) |
| 105 | + |
| 106 | + scraper_selenium_firefox = ChromiumLoader(urls=urls_to_scrape, backend="selenium", headless=True, browser_name = "firefox") |
| 107 | + await test_scraper_with_analysis(scraper_selenium_firefox, urls_to_scrape) |
| 108 | + except ImportError as ie: |
| 109 | + print(f"❌ Selenium ImportError: {ie}") |
| 110 | + except Exception as e: |
| 111 | + print(f"❌ Error initializing Selenium ChromiumLoader: {e}") |
| 112 | + |
| 113 | +if __name__ == "__main__": |
| 114 | + try: |
| 115 | + asyncio.run(main()) |
| 116 | + except KeyboardInterrupt: |
| 117 | + print("❌ Program interrupted by user.") |
| 118 | + except Exception as e: |
| 119 | + print(f"❌ Program crashed: {e}") |
0 commit comments