Skip to content

100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.

feat: removed scrapegraph-py

Marco Vinciguerrad8a4a31b6893
diff --git a/starter_ai_agents/web_scrapping_ai_agent/QUICKSTART.md b/starter_ai_agents/web_scrapping_ai_agent/QUICKSTART.md
deleted file mode 100644
index 4ce07a47..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/QUICKSTART.md
+++ /dev/null
@@ -1,224 +0,0 @@
-# πŸš€ Quick Start Guide - Web Scraping AI Agent
-
-Choose your version and get started in minutes!
-
----
-
-## πŸ“‹ Two Versions Available
-
-### 1️⃣ **Local Library** (Free, Open Source)
-βœ… Best for: Learning, privacy, full control
-πŸ“ Files: `ai_scrapper.py`, `local_ai_scrapper.py`
-
-### 2️⃣ **Cloud SDK** (Managed Service)
-βœ… Best for: Production, scalability, advanced features
-πŸ“ Folder: `scrapegraph_ai_sdk/`
-
----
-
-## πŸƒβ€β™‚οΈ Quick Start - Local Version
-
-### Step 1: Install Dependencies
-```bash
-pip install -r requirements.txt
-```
-
-### Step 2: Get OpenAI API Key
-πŸ‘‰ Sign up at [platform.openai.com](https://platform.openai.com/)
-
-### Step 3: Run the App
-```bash
-streamlit run ai_scrapper.py
-```
-
-### Step 4: Use the App
-1. Enter your OpenAI API key
-2. Select model (GPT-4o recommended)
-3. Enter website URL
-4. Describe what to extract
-5. Click "Scrape"!
-
-**⏱️ Setup Time: ~2 minutes**
-
----
-
-## ☁️ Quick Start - Cloud SDK
-
-### Step 1: Navigate to SDK Folder
-```bash
-cd scrapegraph_ai_sdk/
-```
-
-### Step 2: Install Dependencies
-```bash
-pip install -r requirements.txt
-```
-
-### Step 3: Get ScrapeGraph AI API Key
-πŸ‘‰ Sign up at [scrapegraphai.com](https://scrapegraphai.com)
-
-### Step 4: Set API Key
-```bash
-export SGAI_API_KEY='your-api-key-here'
-```
-
-### Step 5: Quick Test
-```bash
-python quickstart.py
-```
-
-### Step 6: Try Different Features
-
-**SmartScraper** (extract structured data):
-```bash
-python smart_scraper_demo.py
-```
-
-**SearchScraper** (AI web search):
-```bash
-python search_scraper_demo.py
-```
-
-**SmartCrawler** (multi-page scraping):
-```bash
-python smart_crawler_demo.py
-```
-
-**Interactive App**:
-```bash
-streamlit run scrapegraph_app.py
-```
-
-**⏱️ Setup Time: ~1 minute**
-
----
-
-## 🎯 Which One Should I Choose?
-
-### Choose **Local Library** if you want:
-- πŸ†“ Free solution (pay only for OpenAI API)
-- πŸ”’ Privacy (all processing on your machine)
-- πŸŽ“ Learning and experimentation
-- πŸ› οΈ Full control over the process
-
-### Choose **Cloud SDK** if you want:
-- ⚑ Quick setup (no dependencies)
-- πŸš€ Production-ready scalability
-- ✨ Advanced features (SmartCrawler, SearchScraper, Markdownify)
-- πŸ”„ Automatic updates
-
----
-
-## πŸ’‘ Example Use Cases
-
-### E-commerce Price Monitoring
-```python
-# Local Version
-prompt = "Extract product name, price, and availability"
-
-# Cloud SDK
-response = client.smartscraper(
- website_url="https://shop.example.com/product",
- user_prompt="Extract product name, price, and availability"
-)
-```
-
-### News Aggregation
-```python
-# Cloud SDK only
-response = client.smartscraper(
- user_prompt="Find top 5 tech news articles with titles and summaries",
- num_results=5
-)
-```
-
-### Documentation Scraping
-```python
-# Cloud SDK SmartCrawler
-request_id = client.smartcrawler(
- url="https://docs.example.com",
- user_prompt="Extract all API endpoints and descriptions",
- max_pages=50
-)
-```
-
----
-
-## πŸ†˜ Troubleshooting
-
-### Local Version Issues
-
-**Problem**: `ModuleNotFoundError: No module named 'scrapegraphai'`
-```bash
-# Solution
-pip install scrapegraphai
-```
-
-**Problem**: Scraping is slow
-```
-# Solution: Try a lighter model
-Use GPT-3.5-turbo instead of GPT-4
-```
-
-### Cloud SDK Issues
-
-**Problem**: `SGAI_API_KEY not found`
-```bash
-# Solution
-export SGAI_API_KEY='your-actual-key'
-# Or add to your .bashrc/.zshrc
-```
-
-**Problem**: `Insufficient credits`
-```bash
-# Check balance
-python -c "from scrapegraph_py import Client; print(Client('your-key').get_credits())"
-# Then recharge at scrapegraphai.com
-```
-
----
-
-## πŸ“š Next Steps
-
-### After Getting Started:
-
-1. **Read Full Documentation**
- - Local: Main README.md
- - Cloud SDK: `scrapegraph_ai_sdk/README.md`
-
-2. **Try Advanced Features**
- - Custom output schemas
- - JavaScript rendering
- - Scheduled jobs (SDK only)
-
-3. **Integrate into Your Project**
- - Use as a library in your Python code
- - Build custom workflows
- - Automate data collection
-
----
-
-## πŸ”— Useful Links
-
-### Local Library
-- [ScrapeGraph AI GitHub](https://github.com/VinciGit00/Scrapegraph-ai)
-- [Documentation](https://scrapegraph-ai.readthedocs.io/)
-
-### Cloud SDK
-- [SDK GitHub](https://github.com/ScrapeGraphAI/scrapegraph-sdk)
-- [API Documentation](https://docs.scrapegraphai.com)
-- [Get API Key](https://scrapegraphai.com)
-
----
-
-## πŸ’¬ Need Help?
-
-- πŸ“– Check the README files
-- πŸ’‘ Look at example code in demos
-- πŸ› Report issues on GitHub
-- πŸ“§ Contact: [email protected]
-
----
-
-**Happy Scraping! πŸ•·οΈβœ¨**
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/README.md b/starter_ai_agents/web_scrapping_ai_agent/README.md
index e60ca1d2..8b33228e 100644
--- a/starter_ai_agents/web_scrapping_ai_agent/README.md
+++ b/starter_ai_agents/web_scrapping_ai_agent/README.md
@@ -247,24 +247,3 @@ request_id = client.smartcrawler(
- βœ… You prefer managed service
**πŸ’‘ Pro Tip**: Start with the local version to learn, then switch to SDK for production!
-
----
-
-## πŸ”— Resources
-
-- **ScrapeGraph AI Website**: https://scrapegraphai.com
-- **GitHub Repository**: https://github.com/ScrapeGraphAI/scrapegraph-sdk
-- **Documentation**: https://docs.scrapegraphai.com
-- **Get API Key**: https://scrapegraphai.com
-
----
-
-## πŸ’¬ Support
-
-- πŸ“§ Email: [email protected]
-- πŸ’» GitHub Issues
-- 🌟 Star the repo if you find it useful!
-
----
-
-Made with ❀️ by the ScrapeGraph AI team
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/README.md b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/README.md
deleted file mode 100644
index 07188963..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/README.md
+++ /dev/null
@@ -1,433 +0,0 @@
-# πŸ•·οΈ ScrapeGraph AI SDK - Intelligent Web Scraping
-
-Powerful AI-powered web scraping using the official [ScrapeGraph AI SDK](https://github.com/ScrapeGraphAI/scrapegraph-sdk). Extract structured data, convert to markdown, crawl multiple pages, and perform AI-powered web searches.
-
-## πŸ“‹ Overview
-
-ScrapeGraph AI SDK provides cloud-based AI scraping capabilities with natural language prompts. No complex selectors or XPath needed - just describe what you want to extract!
-
-### 🌟 Key Features
-
-- πŸ€– **SmartScraper**: Extract structured data with natural language
-- πŸ” **SearchScraper**: AI-powered web search with structured results
-- πŸ“ **Markdownify**: Convert webpages to clean markdown
-- πŸ•·οΈ **SmartCrawler**: Intelligent multi-page crawling
-- πŸ€– **AgenticScraper**: Automated browser actions
-- ⏰ **Scheduled Jobs**: Cron-based scraping workflows
-- πŸ’³ **Credits Management**: Monitor API usage
-
-## πŸš€ Features
-
-- **Natural Language Extraction**: No CSS selectors needed
-- **Schema Validation**: Structured output with Pydantic
-- **Multiple Formats**: JSON, Markdown, custom schemas
-- **High Performance**: Concurrent processing
-- **Enterprise Ready**: Production-grade reliability
-
-## πŸ“¦ Installation
-
-Install the required dependencies:
-
-```bash
-pip install -r requirements.txt
-```
-
-## πŸ”‘ Setup
-
-1. Get your API key from [ScrapeGraph AI](https://scrapegraphai.com)
-
-2. Set your API key as environment variable:
-
-```bash
-export SGAI_API_KEY='your-api-key-here'
-```
-
-## πŸ’» Usage
-
-### Basic Smart Scraping
-
-Run the basic scraper demo:
-
-```bash
-python smart_scraper_demo.py
-```
-
-### Interactive Web App
-
-Run the Streamlit app for interactive scraping:
-
-```bash
-streamlit run scrapegraph_app.py
-```
-
-### Search Scraping
-
-Run the search scraper:
-
-```bash
-python search_scraper_demo.py
-```
-
-### Smart Crawler
-
-Run the multi-page crawler:
-
-```bash
-python smart_crawler_demo.py
-```
-
-## πŸ“š Examples
-
-### 1. SmartScraper - Extract Product Data
-
-```python
-from scrapegraph_py import Client
-
-client = Client(api_key="your-api-key")
-
-# Extract product information
-response = client.smartscraper(
- website_url="https://example.com/product",
- user_prompt="Extract product name, price, description, and availability"
-)
-
-print(response.result)
-```
-
-### 2. SearchScraper - AI Web Search
-
-```python
-# Search and extract structured data
-response = client.smartscraper(
- user_prompt="Find the top 5 AI news websites with their names, URLs, and descriptions",
- num_results=5
-)
-
-for result in response.result:
- print(f"{result['name']}: {result['url']}")
-```
-
-### 3. Markdownify - Convert to Markdown
-
-```python
-# Convert webpage to markdown
-response = client.markdownify(
- website_url="https://example.com/article"
-)
-
-print(response.result) # Clean markdown output
-```
-
-### 4. SmartCrawler - Multi-page Extraction
-
-```python
-# Crawl and extract from multiple pages
-request_id = client.smartcrawler(
- website_url="https://docs.example.com",
- user_prompt="Extract all API endpoints with their methods and descriptions",
- max_pages=10,
- depth=2
-)
-
-# Fetch results
-results = client.smartcrawler_get(request_id)
-```
-
-### 5. Schema Validation with Pydantic
-
-```python
-from pydantic import BaseModel, Field
-
-class Product(BaseModel):
- name: str
- price: float
- in_stock: bool
- rating: float = Field(ge=0, le=5)
-
-# Extract with schema validation
-response = client.smartscraper(
- website_url="https://example.com/product",
- user_prompt="Extract product details",
- output_schema=Product.model_json_schema()
-)
-
-product = Product(**response.result)
-```
-
-## 🎯 Use Cases
-
-### E-commerce Data Extraction
-
-```python
-# Extract product catalog
-products = client.smartscraper(
- website_url="https://shop.example.com",
- user_prompt="Extract all products with name, price, image, and availability"
-)
-```
-
-### News & Content Aggregation
-
-```python
-# Convert articles to markdown for processing
-article_md = client.markdownify(
- website_url="https://news.example.com/article"
-)
-```
-
-### Competitive Intelligence
-
-```python
-# Search and analyze competitor data
-competitors = client.smartscraper(
- user_prompt="Find top 10 SaaS companies in AI space with pricing info",
- num_results=10
-)
-```
-
-### Documentation Scraping
-
-```python
-# Crawl entire documentation site
-request_id = client.smartcrawler(
- website_url="https://docs.example.com",
- user_prompt="Extract all function signatures, parameters, and examples",
- max_pages=50
-)
-```
-
-## πŸ”§ Advanced Features
-
-### Custom Output Schemas
-
-Define exactly what data you want:
-
-```python
-schema = {
- "type": "object",
- "properties": {
- "title": {"type": "string"},
- "author": {"type": "string"},
- "date": {"type": "string", "format": "date"},
- "content": {"type": "string"},
- "tags": {"type": "array", "items": {"type": "string"}}
- }
-}
-
-response = client.smartscraper(
- website_url="https://blog.example.com/post",
- user_prompt="Extract blog post information",
- output_schema=schema
-)
-```
-
-### JavaScript Rendering
-
-For dynamic Single Page Applications:
-
-```python
-response = client.smartscraper(
- website_url="https://spa.example.com",
- user_prompt="Extract data",
- render_heavy_js=True # Enable JS rendering
-)
-```
-
-### Stealth Mode
-
-Avoid bot detection:
-
-```python
-response = client.smartscraper(
- website_url="https://protected-site.com",
- user_prompt="Extract data",
- stealth=True # Enable stealth mode
-)
-```
-
-### Scheduled Jobs
-
-Create recurring scraping tasks:
-
-```python
-# Create scheduled job (daily at 9 AM)
-job = client.create_scheduled_job(
- name="Daily Product Scrape",
- schedule="0 9 * * *", # Cron expression
- scraper_type="smartscraper",
- config={
- "website_url": "https://shop.example.com",
- "user_prompt": "Extract all products"
- }
-)
-
-# List all scheduled jobs
-jobs = client.list_scheduled_jobs()
-
-# Get job execution history
-history = client.get_job_history(job.id)
-```
-
-## πŸ“Š Comparison with Local Library
-
-| Feature | SDK (Cloud API) | Local Library |
-|---------|----------------|---------------|
-| Setup | API key only | Full installation |
-| Processing | Cloud-based | Local compute |
-| Scalability | Unlimited | Hardware limited |
-| Maintenance | Managed | Self-managed |
-| Credits | Pay-per-use | Free (local) |
-| Speed | Very fast | Depends on hardware |
-| Features | All features | Core features |
-
-**Use SDK when:**
-- βœ… You want managed infrastructure
-- βœ… You need high scalability
-- βœ… You prefer pay-per-use pricing
-- βœ… You want latest features
-
-**Use Local Library when:**
-- βœ… You have sensitive data
-- βœ… You prefer self-hosted
-- βœ… You have available compute
-- βœ… You want full control
-
-## πŸ’° Credits & Pricing
-
-Different operations use different credit amounts:
-
-- **SmartScraper**: 10 credits per page
-- **Markdownify**: 2 credits per page
-- **SearchScraper**: 10 credits per result
-- **SmartCrawler**: Variable (based on pages)
-- **Scrape**: 1 credit per page
-
-Check your credits:
-
-```python
-balance = client.get_credits()
-print(f"Available credits: {balance.credits}")
-```
-
-## πŸ”— Integrations
-
-ScrapeGraph AI SDK integrates with:
-
-- **LLM Frameworks**: Langchain, LlamaIndex, Crew.ai, CamelAI
-- **Low-code**: Pipedream, Bubble, Zapier, n8n, LangFlow
-- **MCP Server**: Model Context Protocol support
-
-See the [integration docs](https://docs.scrapegraphai.com/integrations) for details.
-
-## πŸ“– API Reference
-
-### Client
-
-```python
-from scrapegraph_py import Client
-
-client = Client(api_key="your-api-key")
-```
-
-### SmartScraper
-
-```python
-response = client.smartscraper(
- website_url: str | None = None,
- website_html: str | None = None,
- user_prompt: str,
- output_schema: dict | None = None,
- render_heavy_js: bool = False,
- stealth: bool = False
-)
-```
-
-### SearchScraper
-
-```python
-response = client.smartscraper(
- user_prompt: str,
- num_results: int = 3,
- output_schema: dict | None = None
-)
-```
-
-### Markdownify
-
-```python
-response = client.markdownify(
- website_url: str,
- render_heavy_js: bool = False
-)
-```
-
-### SmartCrawler
-
-```python
-request_id = client.smartcrawler(
- url: str,
- user_prompt: str,
- max_pages: int | None = None,
- depth: int | None = None,
- same_domain_only: bool = True
-)
-
-results = client.smartcrawler_get(request_id)
-```
-
-## πŸ› Troubleshooting
-
-### Common Issues
-
-**Issue**: `Authentication failed`
-```bash
-# Solution: Check your API key
-export SGAI_API_KEY='your-actual-key'
-```
-
-**Issue**: `Insufficient credits`
-```python
-# Solution: Check balance and recharge
-balance = client.get_credits()
-print(f"Credits: {balance.credits}")
-```
-
-**Issue**: `Rate limit exceeded`
-```python
-# Solution: Add delays between requests
-import time
-time.sleep(1) # Wait 1 second between calls
-```
-
-## 🀝 Contributing
-
-Contributions welcome! Feel free to:
-- Report bugs
-- Suggest features
-- Submit pull requests
-- Improve documentation
-
-## πŸ“„ License
-
-This example code is provided as-is for educational purposes.
-ScrapeGraph AI SDK is licensed under MIT License.
-
-## πŸ”— Resources
-
-- **GitHub**: https://github.com/ScrapeGraphAI/scrapegraph-sdk
-- **Documentation**: https://docs.scrapegraphai.com
-- **API Docs**: https://docs.scrapegraphai.com/api
-- **Python SDK**: https://docs.scrapegraphai.com/sdk/python
-- **JavaScript SDK**: https://docs.scrapegraphai.com/sdk/javascript
-- **Get API Key**: https://scrapegraphai.com
-
-## πŸ’¬ Support
-
-- πŸ“§ Email: [email protected]
-- πŸ’» GitHub Issues: [Create an issue](https://github.com/ScrapeGraphAI/scrapegraph-sdk/issues)
-- 🌟 Feature Requests: [Request a feature](https://github.com/ScrapeGraphAI/scrapegraph-sdk/issues/new)
-
----
-
-Made with ❀️ by [ScrapeGraph AI](https://scrapegraphai.com)
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/config.example b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/config.example
deleted file mode 100644
index 6c2cb80d..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/config.example
+++ /dev/null
@@ -1,7 +0,0 @@
-# ScrapeGraph AI Configuration Example
-# Copy this to .env and add your API key
-
-SGAI_API_KEY=your-api-key-here
-
-# Get your API key at: https://scrapegraphai.com
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/quickstart.py b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/quickstart.py
deleted file mode 100644
index 2c0b21a7..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/quickstart.py
+++ /dev/null
@@ -1,146 +0,0 @@
-"""
-ScrapeGraph AI Quick Start
-Quick test to verify installation and basic functionality
-"""
-
-import os
-
-
-def check_installation():
- """Verify ScrapeGraph AI SDK is installed."""
- try:
- from scrapegraph_py import Client
- print("βœ… scrapegraph-py is installed")
- return True
- except ImportError:
- print("❌ scrapegraph-py not found")
- print("πŸ’‘ Install with: pip install scrapegraph-py")
- return False
-
-
-def check_api_key():
- """Check if API key is configured."""
- api_key = os.getenv("SGAI_API_KEY")
- if api_key:
- print(f"βœ… API key found: {api_key[:10]}...")
- return api_key
- else:
- print("❌ SGAI_API_KEY not found")
- print("πŸ’‘ Get your API key at: https://scrapegraphai.com")
- print(" Then set it: export SGAI_API_KEY='your-key'")
- return None
-
-
-def test_connection(api_key):
- """Test API connection."""
- from scrapegraph_py import Client
-
- try:
- client = Client(api_key=api_key)
- balance = client.get_credits()
- print(f"βœ… Connection successful!")
- print(f"πŸ’³ Available credits: {balance.credits}")
- return client
- except Exception as e:
- print(f"❌ Connection failed: {e}")
- return None
-
-
-def quick_scrape_test(client):
- """Run a quick scraping test."""
- print("\n" + "=" * 60)
- print("Running quick scrape test...")
- print("=" * 60)
-
- # Simple HTML to scrape
- html = """
- <html>
- <body>
- <h1>Welcome to ScrapeGraph AI</h1>
- <div class="features">
- <div class="feature">
- <h3>SmartScraper</h3>
- <p>Extract structured data with natural language</p>
- </div>
- <div class="feature">
- <h3>SearchScraper</h3>
- <p>AI-powered web search</p>
- </div>
- </div>
- </body>
- </html>
- """
-
- try:
- response = client.smartscraper(
- website_html=html,
- user_prompt="Extract all feature names and descriptions"
- )
-
- print("\nβœ… Scrape successful!")
- print("\nπŸ“Š Results:")
- import json
- print(json.dumps(response.result, indent=2))
-
- return True
-
- except Exception as e:
- print(f"\n❌ Scrape failed: {e}")
- return False
-
-
-def main():
- """Run quick start checks."""
- print("=" * 60)
- print("πŸ•·οΈ SCRAPEGRAPH AI - QUICK START")
- print("=" * 60)
- print()
-
- # 1. Check installation
- if not check_installation():
- return False
-
- print()
-
- # 2. Check API key
- api_key = check_api_key()
- if not api_key:
- return False
-
- print()
-
- # 3. Test connection
- client = test_connection(api_key)
- if not client:
- return False
-
- # 4. Quick scrape test
- success = quick_scrape_test(client)
-
- print("\n" + "=" * 60)
- if success:
- print("✨ Quick start completed successfully!")
- print("\nπŸ’‘ Next steps:")
- print(" 1. Run full demo: python smart_scraper_demo.py")
- print(" 2. Try search: python search_scraper_demo.py")
- print(" 3. Launch app: streamlit run scrapegraph_app.py")
- else:
- print("⚠️ Quick start completed with errors")
- print("πŸ’‘ Check the error messages above")
-
- print("=" * 60)
-
- return success
-
-
-if __name__ == "__main__":
- try:
- success = main()
- exit(0 if success else 1)
- except KeyboardInterrupt:
- print("\n\n⚠️ Interrupted by user")
- exit(1)
- except Exception as e:
- print(f"\n❌ Unexpected error: {e}")
- exit(1)
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/requirements.txt b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/requirements.txt
deleted file mode 100644
index 003d4527..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/requirements.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-scrapegraph-py>=1.41.0
-streamlit>=1.28.0
-pydantic>=2.0.0
-python-dotenv>=1.0.0
-pandas>=2.0.0
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/scrapegraph_app.py b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/scrapegraph_app.py
deleted file mode 100644
index 33627b74..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/scrapegraph_app.py
+++ /dev/null
@@ -1,392 +0,0 @@
-"""
-ScrapeGraph AI Interactive Streamlit App
-Comprehensive web scraping interface with all features
-"""
-
-import streamlit as st
-from scrapegraph_py import Client
-import json
-import os
-from typing import Optional
-import time
-
-
-def init_client() -> Optional[Client]:
- """Initialize ScrapeGraph AI client."""
- api_key = st.session_state.get("api_key") or os.getenv("SGAI_API_KEY")
-
- if not api_key:
- st.error("❌ Please enter your ScrapeGraph AI API key")
- st.info("Get your API key at: https://scrapegraphai.com")
- return None
-
- try:
- client = Client(api_key=api_key)
- # Try to get credits to verify key
- balance = client.get_credits()
- st.sidebar.success(f"πŸ’³ Credits: {balance.credits}")
- return client
- except Exception as e:
- st.error(f"❌ Error initializing client: {e}")
- return None
-
-
-def smart_scraper_tab(client: Client):
- """SmartScraper interface."""
- st.header("πŸ€– SmartScraper")
- st.markdown("Extract structured data from websites using natural language")
-
- col1, col2 = st.columns([2, 1])
-
- with col1:
- url = st.text_input("Website URL", placeholder="https://example.com")
-
- with col2:
- render_js = st.checkbox("Render JavaScript", help="Enable for SPAs")
-
- prompt = st.text_area(
- "What to extract?",
- placeholder="Extract product names, prices, and availability",
- height=100
- )
-
- # Advanced options
- with st.expander("βš™οΈ Advanced Options"):
- use_html = st.checkbox("Use HTML input instead of URL")
-
- if use_html:
- html_content = st.text_area("HTML Content", height=200)
-
- use_schema = st.checkbox("Define output schema")
-
- if use_schema:
- schema_input = st.text_area(
- "JSON Schema",
- value='{\n "type": "object",\n "properties": {\n "items": {"type": "array"}\n }\n}',
- height=200
- )
-
- stealth = st.checkbox("Enable stealth mode")
-
- if st.button("πŸš€ Extract Data", key="smart_scraper_btn"):
- if not prompt:
- st.error("Please enter an extraction prompt")
- return
-
- if not use_html and not url:
- st.error("Please enter a URL")
- return
-
- if use_html and not html_content:
- st.error("Please enter HTML content")
- return
-
- with st.spinner("Extracting data..."):
- try:
- # Prepare parameters
- params = {
- "user_prompt": prompt,
- "render_heavy_js": render_js,
- }
-
- if use_html:
- params["website_html"] = html_content
- else:
- params["website_url"] = url
-
- if use_schema:
- try:
- params["output_schema"] = json.loads(schema_input)
- except json.JSONDecodeError:
- st.error("Invalid JSON schema")
- return
-
- if stealth:
- params["stealth"] = True
-
- # Make request
- response = client.smartscraper(**params)
-
- # Display results
- st.success("βœ… Data extracted successfully!")
-
- st.subheader("πŸ“Š Results")
- st.json(response.result)
-
- # Download button
- st.download_button(
- label="πŸ’Ύ Download JSON",
- data=json.dumps(response.result, indent=2),
- file_name="scraped_data.json",
- mime="application/json"
- )
-
- except Exception as e:
- st.error(f"❌ Error: {e}")
-
-
-def search_scraper_tab(client: Client):
- """SearchScraper interface."""
- st.header("πŸ” SearchScraper")
- st.markdown("AI-powered web search with structured results")
-
- query = st.text_area(
- "Search Query",
- placeholder="Find the top 5 AI news websites with descriptions",
- height=100
- )
-
- col1, col2 = st.columns(2)
-
- with col1:
- num_results = st.slider("Number of results", 1, 10, 5)
-
- with col2:
- use_schema = st.checkbox("Define result schema")
-
- if use_schema:
- schema_input = st.text_area(
- "JSON Schema",
- value='{\n "type": "object",\n "properties": {\n "results": {"type": "array"}\n }\n}',
- height=200
- )
-
- if st.button("πŸ” Search", key="search_btn"):
- if not query:
- st.error("Please enter a search query")
- return
-
- with st.spinner("Searching..."):
- try:
- params = {
- "user_prompt": query,
- "num_results": num_results
- }
-
- if use_schema:
- try:
- params["output_schema"] = json.loads(schema_input)
- except json.JSONDecodeError:
- st.error("Invalid JSON schema")
- return
-
- response = client.smartscraper(**params)
-
- st.success("βœ… Search completed!")
-
- st.subheader("πŸ“Š Results")
- st.json(response.result)
-
- st.download_button(
- label="πŸ’Ύ Download Results",
- data=json.dumps(response.result, indent=2),
- file_name="search_results.json",
- mime="application/json"
- )
-
- except Exception as e:
- st.error(f"❌ Error: {e}")
-
-
-def markdownify_tab(client: Client):
- """Markdownify interface."""
- st.header("πŸ“ Markdownify")
- st.markdown("Convert any webpage to clean markdown")
-
- url = st.text_input("Website URL", placeholder="https://example.com/article")
-
- render_js = st.checkbox("Render JavaScript", help="Enable for SPAs")
-
- if st.button("πŸ”„ Convert to Markdown", key="markdown_btn"):
- if not url:
- st.error("Please enter a URL")
- return
-
- with st.spinner("Converting..."):
- try:
- response = client.markdownify(
- website_url=url,
- render_heavy_js=render_js
- )
-
- st.success("βœ… Converted successfully!")
-
- st.subheader("πŸ“„ Markdown Output")
- st.code(response.result, language="markdown")
-
- st.download_button(
- label="πŸ’Ύ Download Markdown",
- data=response.result,
- file_name="content.md",
- mime="text/markdown"
- )
-
- except Exception as e:
- st.error(f"❌ Error: {e}")
-
-
-def smart_crawler_tab(client: Client):
- """SmartCrawler interface."""
- st.header("πŸ•·οΈ SmartCrawler")
- st.markdown("Intelligently crawl and extract from multiple pages")
-
- st.warning("⚠️ SmartCrawler is asynchronous and may take several minutes")
-
- url = st.text_input("Start URL", placeholder="https://example.com")
-
- prompt = st.text_area(
- "What to extract?",
- placeholder="Extract all page titles and descriptions",
- height=100
- )
-
- col1, col2, col3 = st.columns(3)
-
- with col1:
- max_pages = st.number_input("Max pages", 1, 100, 10)
-
- with col2:
- depth = st.number_input("Crawl depth", 1, 5, 2)
-
- with col3:
- same_domain = st.checkbox("Same domain only", value=True)
-
- col_mode1, col_mode2 = st.columns(2)
-
- with col_mode1:
- extraction_mode = st.selectbox("Mode", ["ai", "markdown"])
-
- if st.button("πŸš€ Start Crawler", key="crawler_btn"):
- if not url:
- st.error("Please enter a URL")
- return
-
- with st.spinner("Starting crawler..."):
- try:
- params = {
- "url": url,
- "extraction_mode": extraction_mode,
- "max_pages": max_pages,
- "depth": depth,
- "same_domain_only": same_domain
- }
-
- if extraction_mode == "ai" and prompt:
- params["prompt"] = prompt
-
- request_id = client.smartcrawler(**params)
-
- st.success(f"βœ… Crawler started!")
- st.info(f"Request ID: `{request_id}`")
-
- st.markdown("### ⏳ Fetching results...")
- progress_bar = st.progress(0)
- status_text = st.empty()
-
- # Poll for results
- max_attempts = 30
- for i in range(max_attempts):
- try:
- results = client.smartcrawler_get(request_id)
-
- if results:
- progress_bar.progress(100)
- status_text.success("βœ… Crawl completed!")
-
- st.subheader("πŸ“Š Results")
- st.json(results)
-
- st.download_button(
- label="πŸ’Ύ Download Results",
- data=json.dumps(results, indent=2),
- file_name="crawl_results.json",
- mime="application/json"
- )
- break
- except Exception as e:
- if "not ready" in str(e).lower():
- progress = int((i + 1) / max_attempts * 100)
- progress_bar.progress(progress)
- status_text.text(f"Processing... ({i + 1}/{max_attempts})")
- time.sleep(2)
- else:
- raise
- else:
- st.warning("⏰ Crawler is still processing. Check back later with the request ID.")
-
- except Exception as e:
- st.error(f"❌ Error: {e}")
-
-
-def main():
- st.set_page_config(
- page_title="ScrapeGraph AI SDK",
- page_icon="πŸ•·οΈ",
- layout="wide"
- )
-
- st.title("πŸ•·οΈ ScrapeGraph AI SDK")
- st.markdown("Intelligent web scraping powered by AI")
-
- # Sidebar
- with st.sidebar:
- st.header("βš™οΈ Configuration")
-
- api_key = st.text_input(
- "API Key",
- type="password",
- value=os.getenv("SGAI_API_KEY", ""),
- help="Get your API key at scrapegraphai.com"
- )
-
- if api_key:
- st.session_state.api_key = api_key
-
- st.markdown("---")
-
- st.markdown("### πŸ”— Links")
- st.markdown("[GitHub](https://github.com/ScrapeGraphAI/scrapegraph-sdk)")
- st.markdown("[Documentation](https://docs.scrapegraphai.com)")
- st.markdown("[Get API Key](https://scrapegraphai.com)")
-
- st.markdown("---")
-
- st.markdown("### πŸ’‘ Features")
- st.markdown("""
- - πŸ€– SmartScraper
- - πŸ” SearchScraper
- - πŸ“ Markdownify
- - πŸ•·οΈ SmartCrawler
- """)
-
- # Initialize client
- client = init_client()
-
- if not client:
- st.info("πŸ‘† Please enter your API key in the sidebar to get started")
- return
-
- # Main tabs
- tab1, tab2, tab3, tab4 = st.tabs([
- "πŸ€– SmartScraper",
- "πŸ” SearchScraper",
- "πŸ“ Markdownify",
- "πŸ•·οΈ SmartCrawler"
- ])
-
- with tab1:
- smart_scraper_tab(client)
-
- with tab2:
- search_scraper_tab(client)
-
- with tab3:
- markdownify_tab(client)
-
- with tab4:
- smart_crawler_tab(client)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/search_scraper_demo.py b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/search_scraper_demo.py
deleted file mode 100644
index 534c63bd..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/search_scraper_demo.py
+++ /dev/null
@@ -1,296 +0,0 @@
-"""
-ScrapeGraph AI SearchScraper Demo
-AI-powered web search with structured data extraction
-"""
-
-import os
-from scrapegraph_py import Client
-from pydantic import BaseModel
-from typing import List
-import json
-
-
-class SearchResult(BaseModel):
- """Schema for search results."""
- title: str
- url: str
- description: str
-
-
-class SearchResults(BaseModel):
- """Schema for multiple search results."""
- results: List[SearchResult]
-
-
-def basic_search_example():
- """Basic AI-powered web search."""
-
- print("=" * 80)
- print("πŸ” SCRAPEGRAPH AI - SEARCH SCRAPER DEMO")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- print("\n❌ Error: SGAI_API_KEY environment variable not set")
- print("πŸ’‘ Get your API key at: https://scrapegraphai.com")
- return
-
- client = Client(api_key=api_key)
-
- # Check credits
- try:
- balance = client.get_credits()
- print(f"\nπŸ’³ Available credits: {balance.credits}")
- except Exception as e:
- print(f"\n⚠️ Could not check credits: {e}")
-
- print("\n" + "=" * 80)
- print("Example 1: Basic Web Search")
- print("=" * 80)
-
- query = "Top 5 AI news websites"
- print(f"\nπŸ” Query: {query}")
-
- try:
- response = client.smartscraper(
- user_prompt=query,
- num_results=5
- )
-
- print("\nβœ… Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def structured_search_example():
- """Search with structured output schema."""
-
- print("\n" + "=" * 80)
- print("Example 2: Structured Search Results")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- query = "Find the best Python web scraping libraries with their GitHub stars and documentation links"
- print(f"\nπŸ” Query: {query}")
-
- schema = {
- "type": "object",
- "properties": {
- "libraries": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "name": {"type": "string"},
- "description": {"type": "string"},
- "github_url": {"type": "string"},
- "stars": {"type": "string"},
- "docs_url": {"type": "string"}
- }
- }
- }
- }
- }
-
- try:
- response = client.smartscraper(
- user_prompt=query,
- num_results=5,
- output_schema=schema
- )
-
- print("\nβœ… Structured Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def competitive_intelligence_example():
- """Use search for competitive intelligence."""
-
- print("\n" + "=" * 80)
- print("Example 3: Competitive Intelligence")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- query = "Top SaaS companies in the web scraping space with pricing and features"
- print(f"\nπŸ” Query: {query}")
-
- schema = {
- "type": "object",
- "properties": {
- "companies": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "company_name": {"type": "string"},
- "website": {"type": "string"},
- "pricing_model": {"type": "string"},
- "key_features": {"type": "array", "items": {"type": "string"}},
- "target_market": {"type": "string"}
- }
- }
- }
- }
- }
-
- try:
- response = client.smartscraper(
- user_prompt=query,
- num_results=5,
- output_schema=schema
- )
-
- print("\nβœ… Competitive Analysis:")
- if "companies" in response.result:
- for company in response.result["companies"]:
- print(f"\n 🏒 {company.get('company_name', 'N/A')}")
- print(f" Website: {company.get('website', 'N/A')}")
- print(f" Pricing: {company.get('pricing_model', 'N/A')}")
- if 'key_features' in company:
- print(f" Features: {', '.join(company['key_features'][:3])}")
- else:
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def news_aggregation_example():
- """Aggregate news articles on a topic."""
-
- print("\n" + "=" * 80)
- print("Example 4: News Aggregation")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- query = "Latest AI breakthroughs in 2024 with article titles, dates, and summaries"
- print(f"\nπŸ” Query: {query}")
-
- schema = {
- "type": "object",
- "properties": {
- "articles": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "title": {"type": "string"},
- "source": {"type": "string"},
- "url": {"type": "string"},
- "date": {"type": "string"},
- "summary": {"type": "string"}
- }
- }
- }
- }
- }
-
- try:
- response = client.smartscraper(
- user_prompt=query,
- num_results=5,
- output_schema=schema
- )
-
- print("\nβœ… News Articles:")
- if "articles" in response.result:
- for i, article in enumerate(response.result["articles"], 1):
- print(f"\n πŸ“° Article {i}: {article.get('title', 'N/A')}")
- print(f" Source: {article.get('source', 'N/A')}")
- print(f" Date: {article.get('date', 'N/A')}")
- print(f" URL: {article.get('url', 'N/A')}")
- summary = article.get('summary', 'N/A')
- if len(summary) > 100:
- summary = summary[:100] + "..."
- print(f" Summary: {summary}")
- else:
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def market_research_example():
- """Perform market research using search."""
-
- print("\n" + "=" * 80)
- print("Example 5: Market Research")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- query = "E-commerce platforms for small businesses with features and pricing"
- print(f"\nπŸ” Query: {query}")
-
- try:
- response = client.smartscraper(
- user_prompt=query,
- num_results=5
- )
-
- print("\nβœ… Market Research Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def main():
- """Run all search examples."""
-
- # Basic search
- basic_search_example()
-
- # Structured search
- structured_search_example()
-
- # Competitive intelligence
- competitive_intelligence_example()
-
- # News aggregation
- news_aggregation_example()
-
- # Market research
- market_research_example()
-
- print("\n" + "=" * 80)
- print("πŸŽ‰ Search Demo completed!")
- print("\nπŸ’‘ Use Cases:")
- print(" - Competitive analysis")
- print(" - Market research")
- print(" - News aggregation")
- print(" - Lead generation")
- print(" - Content discovery")
- print("\nπŸ”— Resources:")
- print(" - GitHub: https://github.com/ScrapeGraphAI/scrapegraph-sdk")
- print(" - Docs: https://docs.scrapegraphai.com")
- print("=" * 80)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_crawler_demo.py b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_crawler_demo.py
deleted file mode 100644
index 5cbb9767..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_crawler_demo.py
+++ /dev/null
@@ -1,298 +0,0 @@
-"""
-ScrapeGraph AI SmartCrawler Demo
-Intelligently crawl and extract data from multiple pages
-"""
-
-import os
-from scrapegraph_py import Client
-import json
-import time
-
-
-def basic_crawler_example():
- """Basic multi-page crawling."""
-
- print("=" * 80)
- print("πŸ•·οΈ SCRAPEGRAPH AI - SMART CRAWLER DEMO")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- print("\n❌ Error: SGAI_API_KEY environment variable not set")
- print("πŸ’‘ Get your API key at: https://scrapegraphai.com")
- return
-
- client = Client(api_key=api_key)
-
- # Check credits
- try:
- balance = client.get_credits()
- print(f"\nπŸ’³ Available credits: {balance.credits}")
- except Exception as e:
- print(f"\n⚠️ Could not check credits: {e}")
-
- print("\n" + "=" * 80)
- print("Example 1: Basic Website Crawling")
- print("=" * 80)
-
- # Start crawling
- url = "https://www.scrapethissite.com/pages/"
- prompt = "Extract all page titles and descriptions"
-
- print(f"\nπŸ” Starting crawler...")
- print(f" URL: {url}")
- print(f" Prompt: {prompt}")
- print(f" Max pages: 5")
- print(f" Depth: 1")
-
- try:
- # Initiate crawl
- request_id = client.smartcrawler(
- url=url,
- user_prompt=prompt,
- max_pages=5,
- depth=1,
- same_domain_only=True
- )
-
- print(f"\nβœ… Crawler started!")
- print(f" Request ID: {request_id}")
- print("\n⏳ Waiting for results...")
-
- # Poll for results
- max_attempts = 30
- for attempt in range(max_attempts):
- try:
- results = client.smartcrawler_get(request_id)
-
- if results:
- print("\nβœ… Crawl completed!")
- print(f"\nπŸ“Š Results:")
- print(json.dumps(results, indent=2))
- break
-
- except Exception as e:
- if "not ready" in str(e).lower() or "pending" in str(e).lower():
- print(f" Attempt {attempt + 1}/{max_attempts}...")
- time.sleep(2)
- else:
- raise
- else:
- print("\n⏰ Timeout waiting for results")
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def documentation_crawler_example():
- """Crawl documentation sites."""
-
- print("\n" + "=" * 80)
- print("Example 2: Documentation Crawling")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- # Example: Crawl a documentation site
- url = "https://docs.python.org/3/"
- prompt = "Extract all function names, descriptions, and code examples"
-
- print(f"\nπŸ” Crawling documentation...")
- print(f" URL: {url}")
- print(f" Max pages: 10")
- print(f" Depth: 2")
-
- try:
- request_id = client.smartcrawler(
- url=url,
- user_prompt=prompt,
- max_pages=10,
- depth=2,
- same_domain_only=True
- )
-
- print(f"\nβœ… Crawler initiated: {request_id}")
- print("⏳ Crawling in progress...")
- print("πŸ’‘ This may take a few minutes for multiple pages")
-
- # Note: In production, you'd poll for results
- # For this demo, we just show how to initiate
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def product_catalog_crawler():
- """Crawl e-commerce product catalogs."""
-
- print("\n" + "=" * 80)
- print("Example 3: Product Catalog Crawling")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- url = "https://www.scrapethissite.com/pages/simple/"
- prompt = "Extract all country information including name, capital, population, and area"
-
- print(f"\nπŸ” Crawling product catalog...")
- print(f" URL: {url}")
- print(f" Extraction mode: AI")
-
- try:
- request_id = client.smartcrawler(
- url=url,
- prompt=prompt,
- extraction_mode="ai",
- max_pages=10,
- depth=1
- )
-
- print(f"\nβœ… Crawler started: {request_id}")
- print("⏳ Processing...")
-
- # Poll for results
- for i in range(20):
- try:
- results = client.smartcrawler_get(request_id)
- if results:
- print("\nβœ… Results ready!")
- print(json.dumps(results, indent=2)[:500] + "...")
- break
- except:
- time.sleep(3)
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def markdown_crawler_example():
- """Crawl and convert pages to markdown."""
-
- print("\n" + "=" * 80)
- print("Example 4: Markdown Conversion Crawler")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- url = "https://www.scrapethissite.com/pages/"
-
- print(f"\nπŸ” Converting pages to markdown...")
- print(f" URL: {url}")
- print(f" Mode: Markdown")
-
- try:
- request_id = client.smartcrawler(
- url=url,
- extraction_mode="markdown",
- max_pages=5,
- depth=1
- )
-
- print(f"\nβœ… Crawler initiated: {request_id}")
- print("⏳ Converting to markdown...")
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def custom_depth_crawl():
- """Demonstrate different crawl depths."""
-
- print("\n" + "=" * 80)
- print("Example 5: Custom Depth Crawling")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- url = "https://www.scrapethissite.com/"
- prompt = "Extract page titles and main content"
-
- print("\nπŸ” Comparing different crawl depths:")
-
- # Depth 1: Only linked pages from start URL
- print("\n Depth 1: Direct links only")
-
- try:
- request_id_1 = client.smartcrawler(
- url=url,
- user_prompt=prompt,
- depth=1,
- max_pages=5
- )
- print(f" Request ID: {request_id_1}")
-
- except Exception as e:
- print(f" Error: {e}")
-
- # Depth 2: Two levels deep
- print("\n Depth 2: Two levels deep")
-
- try:
- request_id_2 = client.smartcrawler(
- url=url,
- user_prompt=prompt,
- depth=2,
- max_pages=10
- )
- print(f" Request ID: {request_id_2}")
-
- except Exception as e:
- print(f" Error: {e}")
-
- print("\nπŸ’‘ Higher depth = more pages discovered")
- print("πŸ’‘ Use max_pages to control costs")
-
-
-def main():
- """Run all crawler examples."""
-
- print("\n⚠️ Note: SmartCrawler is asynchronous and may take time")
- print("πŸ’‘ Results are fetched via polling or webhooks")
-
- # Basic crawler
- basic_crawler_example()
-
- # Documentation crawler
- documentation_crawler_example()
-
- # Product catalog
- product_catalog_crawler()
-
- # Markdown crawler
- markdown_crawler_example()
-
- # Custom depth
- custom_depth_crawl()
-
- print("\n" + "=" * 80)
- print("πŸŽ‰ Crawler Demo completed!")
- print("\nπŸ’‘ Best Practices:")
- print(" - Start with small max_pages to test")
- print(" - Use same_domain_only to avoid following external links")
- print(" - Set appropriate depth based on site structure")
- print(" - Monitor credit usage for large crawls")
- print("\nπŸ”— Resources:")
- print(" - GitHub: https://github.com/ScrapeGraphAI/scrapegraph-sdk")
- print(" - Docs: https://docs.scrapegraphai.com")
- print("=" * 80)
-
-
-if __name__ == "__main__":
- main()
-
diff --git a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_scraper_demo.py b/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_scraper_demo.py
deleted file mode 100644
index 6a11d35b..00000000
--- a/starter_ai_agents/web_scrapping_ai_agent/scrapegraph_ai_sdk/smart_scraper_demo.py
+++ /dev/null
@@ -1,279 +0,0 @@
-"""
-ScrapeGraph AI SmartScraper Demo
-Extract structured data from websites using natural language prompts
-"""
-
-import os
-from scrapegraph_py import Client
-from pydantic import BaseModel, Field
-from typing import List, Optional
-import json
-
-
-def basic_scraping_example():
- """Basic web scraping with natural language."""
-
- print("=" * 80)
- print("πŸ•·οΈ SCRAPEGRAPH AI - SMART SCRAPER DEMO")
- print("=" * 80)
-
- # Initialize client
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- print("\n❌ Error: SGAI_API_KEY environment variable not set")
- print("πŸ’‘ Get your API key at: https://scrapegraphai.com")
- print(" Then run: export SGAI_API_KEY='your-key'")
- return
-
- client = Client(api_key=api_key)
-
- # Check credits
- try:
- balance = client.get_credits()
- print(f"\nπŸ’³ Available credits: {balance.credits}")
- except Exception as e:
- print(f"\n⚠️ Could not check credits: {e}")
-
- print("\n" + "=" * 80)
- print("Example 1: Extract Product Information")
- print("=" * 80)
-
- # Example website (you can change this)
- url = "https://www.scrapethissite.com/pages/simple/"
-
- print(f"\nπŸ” Scraping: {url}")
- print("πŸ“‹ Prompt: Extract country names, capitals, and population")
-
- try:
- response = client.smartscraper(
- website_url=url,
- user_prompt="Extract the first 5 countries with their names, capitals, and population"
- )
-
- print("\nβœ… Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def schema_validation_example():
- """Scraping with Pydantic schema validation."""
-
- print("\n" + "=" * 80)
- print("Example 2: Schema Validation with Pydantic")
- print("=" * 80)
-
- # Define data structure
- class Country(BaseModel):
- name: str
- capital: str
- population: int
- area: Optional[float] = None
-
- class Countries(BaseModel):
- countries: List[Country]
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- url = "https://www.scrapethissite.com/pages/simple/"
-
- print(f"\nπŸ” Scraping: {url}")
- print("πŸ“‹ Using Pydantic schema for validation")
-
- try:
- response = client.smartscraper(
- website_url=url,
- user_prompt="Extract the first 3 countries with name, capital, and population",
- output_schema=Countries.model_json_schema()
- )
-
- # Validate with Pydantic
- countries = Countries(**response.result)
-
- print("\nβœ… Validated Results:")
- for country in countries.countries:
- print(f"\n 🌍 {country.name}")
- print(f" Capital: {country.capital}")
- print(f" Population: {country.population:,}")
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def html_scraping_example():
- """Scrape from HTML string instead of URL."""
-
- print("\n" + "=" * 80)
- print("Example 3: Scraping from HTML String")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- # Sample HTML
- html_content = """
- <html>
- <body>
- <div class="products">
- <div class="product">
- <h2>Laptop Pro</h2>
- <p class="price">$1,299</p>
- <p class="stock">In Stock</p>
- </div>
- <div class="product">
- <h2>Magic Mouse</h2>
- <p class="price">$79</p>
- <p class="stock">Out of Stock</p>
- </div>
- <div class="product">
- <h2>Wireless Keyboard</h2>
- <p class="price">$89</p>
- <p class="stock">In Stock</p>
- </div>
- </div>
- </body>
- </html>
- """
-
- print("\nπŸ“„ Scraping from HTML content")
-
- try:
- response = client.smartscraper(
- website_html=html_content,
- user_prompt="Extract all products with their names, prices, and stock status"
- )
-
- print("\nβœ… Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def custom_schema_example():
- """Use custom JSON schema for precise output structure."""
-
- print("\n" + "=" * 80)
- print("Example 4: Custom JSON Schema")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- # Define custom schema
- schema = {
- "type": "object",
- "properties": {
- "countries": {
- "type": "array",
- "items": {
- "type": "object",
- "properties": {
- "country_name": {"type": "string"},
- "capital_city": {"type": "string"},
- "population_count": {"type": "number"}
- },
- "required": ["country_name", "capital_city", "population_count"]
- }
- }
- },
- "required": ["countries"]
- }
-
- url = "https://www.scrapethissite.com/pages/simple/"
-
- print(f"\nπŸ” Scraping: {url}")
- print("πŸ“‹ Using custom JSON schema")
-
- try:
- response = client.smartscraper(
- website_url=url,
- user_prompt="Extract first 3 countries",
- output_schema=schema
- )
-
- print("\nβœ… Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def spa_rendering_example():
- """Scrape Single Page Applications with JavaScript rendering."""
-
- print("\n" + "=" * 80)
- print("Example 5: JavaScript Rendering for SPAs")
- print("=" * 80)
-
- api_key = os.getenv("SGAI_API_KEY")
- if not api_key:
- return
-
- client = Client(api_key=api_key)
-
- # Example SPA site
- url = "https://www.scrapethissite.com/pages/ajax-javascript/"
-
- print(f"\nπŸ” Scraping SPA: {url}")
- print("βš™οΈ JavaScript rendering: ENABLED")
-
- try:
- response = client.smartscraper(
- website_url=url,
- user_prompt="Extract the years and number of Oscar wins",
- render_heavy_js=True # Enable JS rendering
- )
-
- print("\nβœ… Results:")
- print(json.dumps(response.result, indent=2))
-
- except Exception as e:
- print(f"\n❌ Error: {e}")
-
-
-def main():
- """Run all examples."""
-
- # Basic scraping
- basic_scraping_example()
-
- # Schema validation
- schema_validation_example()
-
- # HTML scraping
- html_scraping_example()
-
- # Custom schema
- custom_schema_example()
-
- # SPA rendering
- spa_rendering_example()
-
- print("\n" + "=" * 80)
- print("πŸŽ‰ Demo completed!")
- print("\nπŸ’‘ Next steps:")
- print(" - Try with your own URLs")
- print(" - Customize the prompts")
- print(" - Define your own schemas")
- print(" - Run the Streamlit app: streamlit run scrapegraph_app.py")
- print("\nπŸ”— Resources:")
- print(" - GitHub: https://github.com/ScrapeGraphAI/scrapegraph-sdk")
- print(" - Docs: https://docs.scrapegraphai.com")
- print("=" * 80)
-
-
-if __name__ == "__main__":
- main()
-