MCPcopy Create free account
hub / github.com/ScrapeGraphAI/scrapecraft / generate_code

Function generate_code

backend/app/agents/tools.py:108–181  ·  view source on GitHub ↗

Generate Python code for the scraping pipeline.

(urls: List[str], extraction_schema: Dict[str, Any])

Source from the content-addressed store, hash-verified

106
107@tool
108def generate_code(urls: List[str], extraction_schema: Dict[str, Any]) -> Dict[str, Any]:
109 """Generate Python code for the scraping pipeline."""
110 code_template = '''import asyncio
111from scrapegraph_py import AsyncClient
112from pydantic import BaseModel
113from typing import List, Optional
114
115# Define the schema
116class DataSchema(BaseModel):
117{schema_fields}
118
119async def scrape_urls(api_key: str):
120 """Execute web scraping for multiple URLs concurrently."""
121 urls = {urls}
122
123 async with AsyncClient(api_key=api_key) as client:
124 tasks = []
125 for url in urls:
126 task = client.smartscraper(
127 website_url=url,
128 user_prompt="Extract data according to the schema",
129 output_schema=DataSchema
130 )
131 tasks.append(task)
132
133 results = await asyncio.gather(*tasks, return_exceptions=True)
134
135 # Process results
136 successful_results = []
137 errors = []
138
139 for i, result in enumerate(results):
140 if isinstance(result, Exception):
141 errors.append({{"url": urls[i], "error": str(result)}})
142 else:
143 successful_results.append({{"url": urls[i], "data": result}})
144
145 return {{"success": successful_results, "errors": errors}}
146
147if __name__ == "__main__":
148 # Replace with your actual API key
149 API_KEY = "your_scrapegraph_api_key"
150
151 # Run the scraper
152 results = asyncio.run(scrape_urls(API_KEY))
153
154 # Print results
155 print(f"Successfully scraped {{len(results['success'])}} URLs")
156 print(f"Failed to scrape {{len(results['errors'])}} URLs")
157
158 # Print data
159 for result in results['success']:
160 print(f"\\nURL: {{result['url']}}")
161 print(f"Data: {{result['data']}}")
162'''
163
164 # Generate schema fields
165 schema_fields = []

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected