Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat: Add Crawlee web scraping node (dual-purpose workflow + AI tool)
trohitg5447724d9a26
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 6d8a9992..2154b5de 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -36,6 +36,7 @@ import { SOCIAL_NODE_TYPES } from './nodeDefinitions/socialNodes';import { APIFY_NODE_TYPES } from './nodeDefinitions/apifyNodes';import { GOOGLE_WORKSPACE_NODE_TYPES } from './nodeDefinitions/googleWorkspaceNodes';import { PROXY_NODE_TYPES } from './nodeDefinitions/proxyNodes';+import { CRAWLEE_NODE_TYPES } from './nodeDefinitions/crawleeNodes';import ParameterPanel from './ParameterPanel';import LocationParameterPanel from './components/LocationParameterPanel';import { useAppStore } from './store/useAppStore';@@ -144,6 +145,9 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {} else if (PROXY_NODE_TYPES.includes(type)) {// Proxy nodes use SquareNode componenttypes[type] = SquareNode;+ } else if (CRAWLEE_NODE_TYPES.includes(type)) {+ // Crawlee web scraping nodes use SquareNode component+ types[type] = SquareNode;} else if (SOCIAL_NODE_TYPES.includes(type)) {// Social nodes use AIAgentNode for multiple output handles supporttypes[type] = AIAgentNode;diff --git a/client/src/components/parameterPanel/InputSection.tsx b/client/src/components/parameterPanel/InputSection.tsxindex 89ff793c..eac92ba0 100644--- a/client/src/components/parameterPanel/InputSection.tsx+++ b/client/src/components/parameterPanel/InputSection.tsx@@ -659,6 +659,20 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =operation: 'string',success: 'boolean',data: 'any'+ },+ // Crawlee web scraping schema+ crawlee: {+ pages: [{+ url: 'string',+ title: 'string',+ content: 'string',+ links: 'array',+ screenshot: 'string'+ }],+ page_count: 'number',+ crawler_type: 'string',+ mode: 'string',+ proxied: 'boolean'}};@@ -713,6 +727,9 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =const proxyNodeTypes = ['proxyRequest', 'proxyStatus', 'proxyConfig'];const isProxyNode = proxyNodeTypes.includes(nodeType);+ // Crawlee web scraping node detection+ const isCrawlee = nodeType === 'crawleeScraper';+// Select appropriate schemaif (isAndroidLocation) {outputSchema = sampleSchemas.androidLocation;@@ -741,6 +758,7 @@ const InputSection: React.FC<InputSectionProps> = ({ nodeId, visible = true }) =isSocialSend ? sampleSchemas.socialSend :isApify ? sampleSchemas.apify :isSearchNode ? sampleSchemas.search :+ isCrawlee ? sampleSchemas.crawlee :{ data: 'any' };}diff --git a/client/src/nodeDefinitions.ts b/client/src/nodeDefinitions.tsindex d307764f..498b2997 100644--- a/client/src/nodeDefinitions.ts+++ b/client/src/nodeDefinitions.ts@@ -24,6 +24,7 @@ import { searchNodes, SEARCH_NODE_TYPES } from './nodeDefinitions/searchNodes';// Consolidated Google Workspace nodes (replaces gmailNodes, calendarNodes, driveNodes, sheetsNodes, tasksNodes, contactsNodes)import { googleWorkspaceNodes, GOOGLE_WORKSPACE_NODE_TYPES } from './nodeDefinitions/googleWorkspaceNodes';import { proxyNodes, PROXY_NODE_TYPES } from './nodeDefinitions/proxyNodes';+import { crawleeNodes, CRAWLEE_NODE_TYPES } from './nodeDefinitions/crawleeNodes';// ============================================================================// MAIN NODE REGISTRY - Combining all modular definitions@@ -51,7 +52,8 @@ export const nodeDefinitions: Record<string, INodeTypeDescription> = {...apifyNodes,...searchNodes,...googleWorkspaceNodes,- ...proxyNodes+ ...proxyNodes,+ ...crawleeNodes};// ============================================================================@@ -148,5 +150,9 @@ export const PROXY_NODES = [...PROXY_NODE_TYPES];+export const CRAWLEE_NODES = [+ ...CRAWLEE_NODE_TYPES+];+// Re-export types and utilities from modular files for external accessexport { createBaseChatModel } from './nodeDefinitions/aiModelNodes';diff --git a/client/src/nodeDefinitions/crawleeNodes.ts b/client/src/nodeDefinitions/crawleeNodes.tsnew file mode 100644index 00000000..99a96b26--- /dev/null+++ b/client/src/nodeDefinitions/crawleeNodes.ts@@ -0,0 +1,254 @@+// Crawlee Web Scraping Node - Static & Browser-based scraping via Crawlee+// Dual-purpose node: works as standalone workflow node AND AI Agent tool++import {+ INodeTypeDescription,+ NodeConnectionType,+} from '../types/INodeProperties';+import { PROXY_PARAMETERS } from './proxyNodes';++export const crawleeNodes: Record<string, INodeTypeDescription> = {+ crawleeScraper: {+ displayName: 'Web Scraper',+ name: 'crawleeScraper',+ icon: '🕷',+ group: ['api', 'tool'],+ version: 1,+ subtitle: 'Crawlee Scraper',+ description: 'Scrape web pages using Crawlee. Supports static HTML (BeautifulSoup) and JS-rendered content (Playwright).',+ defaults: { name: 'Web Scraper', color: '#00D1B2' },+ inputs: [+ {+ name: 'main',+ displayName: 'Input',+ type: 'main' as NodeConnectionType,+ description: 'Scraping input',+ },+ ],+ outputs: [+ {+ name: 'main',+ displayName: 'Output',+ type: 'main' as NodeConnectionType,+ description: 'Scraped content and metadata',+ },+ {+ name: 'tool',+ displayName: 'Tool',+ type: 'main' as NodeConnectionType,+ description: 'Connect to AI Agent tool handle',+ },+ ],+ properties: [+ // ===== TOOL CONFIG =====+ {+ displayName: 'Tool Name',+ name: 'toolName',+ type: 'string',+ default: 'web_scraper',+ description: 'Name of this tool when used by AI Agent',+ },+ {+ displayName: 'Tool Description',+ name: 'toolDescription',+ type: 'string',+ default:+ 'Scrape web pages to extract text content, links, and structured data. Supports static HTML and JavaScript-rendered pages.',+ description: 'Description shown to AI Agent',+ },++ // ===== CRAWLER TYPE =====+ {+ displayName: 'Crawler Type',+ name: 'crawlerType',+ type: 'options',+ options: [+ { name: 'BeautifulSoup (Static HTML)', value: 'beautifulsoup' },+ { name: 'Playwright (Browser)', value: 'playwright' },+ { name: 'Adaptive (Auto-detect)', value: 'adaptive' },+ ],+ default: 'beautifulsoup',+ description:+ 'Crawler engine. BeautifulSoup for static pages, Playwright for JS-rendered content, Adaptive to auto-detect.',+ },++ // ===== URL =====+ {+ displayName: 'URL',+ name: 'url',+ type: 'string',+ default: '',+ required: true,+ placeholder: 'https://example.com',+ description: 'Starting URL to scrape',+ },++ // ===== SCRAPING MODE =====+ {+ displayName: 'Mode',+ name: 'mode',+ type: 'options',+ options: [+ { name: 'Single Page', value: 'single' },+ { name: 'Crawl Links', value: 'crawl' },+ ],+ default: 'single',+ description:+ 'Single page scraping or follow links to crawl multiple pages',+ },++ // ===== CONTENT EXTRACTION =====+ {+ displayName: 'CSS Selector',+ name: 'cssSelector',+ type: 'string',+ default: '',+ placeholder: 'article, .content, #main',+ description:+ 'CSS selector to extract specific content. Leave empty for full page text.',+ },+ {+ displayName: 'Extract Links',+ name: 'extractLinks',+ type: 'boolean',+ default: false,+ description: 'Include all discovered links in the output',+ },++ // ===== CRAWL OPTIONS (shown when mode = crawl) =====+ {+ displayName: 'Link Selector',+ name: 'linkSelector',+ type: 'string',+ default: '',+ placeholder: 'a[href]',+ description:+ 'CSS selector for links to follow. Leave empty to follow all links.',+ displayOptions: { show: { mode: ['crawl'] } },+ },+ {+ displayName: 'URL Pattern',+ name: 'urlPattern',+ type: 'string',+ default: '',+ placeholder: 'https://example.com/blog/**',+ description:+ 'Glob pattern to filter which URLs to crawl. Leave empty for same-domain only.',+ displayOptions: { show: { mode: ['crawl'] } },+ },+ {+ displayName: 'Max Pages',+ name: 'maxPages',+ type: 'number',+ default: 10,+ typeOptions: { minValue: 1, maxValue: 1000 },+ description: 'Maximum number of pages to scrape (1-1000)',+ displayOptions: { show: { mode: ['crawl'] } },+ },+ {+ displayName: 'Max Depth',+ name: 'maxDepth',+ type: 'number',+ default: 2,+ typeOptions: { minValue: 0, maxValue: 10 },+ description: 'Maximum link depth to follow (0 = start URL only)',+ displayOptions: { show: { mode: ['crawl'] } },+ },++ // ===== BROWSER OPTIONS (Playwright/Adaptive only) =====+ {+ displayName: 'Wait For Selector',+ name: 'waitForSelector',+ type: 'string',+ default: '',+ placeholder: '.loaded-content',+ description: 'CSS selector to wait for before extracting content',+ displayOptions: {+ show: { crawlerType: ['playwright', 'adaptive'] },+ },+ },+ {+ displayName: 'Wait Timeout (ms)',+ name: 'waitTimeout',+ type: 'number',+ default: 30000,+ typeOptions: { minValue: 1000, maxValue: 120000 },+ description: 'Maximum time to wait for page load in milliseconds',+ displayOptions: {+ show: { crawlerType: ['playwright', 'adaptive'] },+ },+ },+ {+ displayName: 'Take Screenshot',+ name: 'screenshot',+ type: 'boolean',+ default: false,+ description: 'Capture a screenshot of each page (returned as base64)',+ displayOptions: {+ show: { crawlerType: ['playwright', 'adaptive'] },+ },+ },+ {+ displayName: 'Browser Type',+ name: 'browserType',+ type: 'options',+ options: [+ { name: 'Chromium', value: 'chromium' },+ { name: 'Firefox', value: 'firefox' },+ { name: 'WebKit', value: 'webkit' },+ ],+ default: 'chromium',+ description: 'Browser engine to use for rendering',+ displayOptions: {+ show: { crawlerType: ['playwright', 'adaptive'] },+ },+ },+ {+ displayName: 'Block Resources',+ name: 'blockResources',+ type: 'boolean',+ default: true,+ description:+ 'Block images, fonts, and stylesheets for faster scraping',+ displayOptions: {+ show: { crawlerType: ['playwright', 'adaptive'] },+ },+ },++ // ===== GENERAL OPTIONS =====+ {+ displayName: 'Timeout (seconds)',+ name: 'timeout',+ type: 'number',+ default: 60,+ typeOptions: { minValue: 10, maxValue: 600 },+ description: 'Maximum time for the entire scraping operation',+ },+ {+ displayName: 'Max Concurrency',+ name: 'maxConcurrency',+ type: 'number',+ default: 5,+ typeOptions: { minValue: 1, maxValue: 20 },+ description: 'Maximum concurrent requests',+ },+ {+ displayName: 'Output Format',+ name: 'outputFormat',+ type: 'options',+ options: [+ { name: 'Text', value: 'text' },+ { name: 'HTML', value: 'html' },+ { name: 'Markdown', value: 'markdown' },+ ],+ default: 'text',+ description: 'Format of the extracted content',+ },++ // ===== PROXY PARAMS (shared from proxyNodes) =====+ ...PROXY_PARAMETERS,+ ],+ },+};++export const CRAWLEE_NODE_TYPES = ['crawleeScraper'];diff --git a/client/src/services/executionService.ts b/client/src/services/executionService.tsindex ee33af92..409573cc 100644--- a/client/src/services/executionService.ts+++ b/client/src/services/executionService.ts@@ -10,6 +10,7 @@ import { GOOGLE_WORKSPACE_NODE_TYPES } from '../nodeDefinitions/googleWorkspaceNimport { APIFY_NODE_TYPES } from '../nodeDefinitions/apifyNodes';import { SEARCH_NODE_TYPES } from '../nodeDefinitions/searchNodes';import { TELEGRAM_NODE_TYPES } from '../nodeDefinitions/telegramNodes';+import { CRAWLEE_NODE_TYPES } from '../nodeDefinitions/crawleeNodes';import { Node, Edge } from 'reactflow';import { INodeExecutionData } from '../types/INodeProperties';import { API_CONFIG } from '../config/api';@@ -235,6 +236,8 @@ export class ExecutionService {...GOOGLE_WORKSPACE_NODE_TYPES,// Apify web scraping...APIFY_NODE_TYPES,+ // Crawlee web scraping+ ...CRAWLEE_NODE_TYPES,// Search API nodes...SEARCH_NODE_TYPES,// Telegram Nodesdiff --git a/server/pyproject.toml b/server/pyproject.tomlindex da7d679c..78b9e7e6 100644--- a/server/pyproject.toml+++ b/server/pyproject.toml@@ -66,6 +66,10 @@ dependencies = [# Apify Web Scraping"apify-client>=1.8.0",+ # Crawlee Web Scraping+ "crawlee[beautifulsoup]>=1.4.0",+ "html2text>=2024.2.26",+# Telegram Bot API"python-telegram-bot>=22.6",diff --git a/server/services/ai.py b/server/services/ai.pyindex cf6f0b8e..6ad6deb9 100644--- a/server/services/ai.py+++ b/server/services/ai.py@@ -2499,6 +2499,8 @@ class AIService:'proxyRequest': 'proxy_request','proxyConfig': 'proxy_config','proxyStatus': 'proxy_status',+ # Crawlee web scraping (dual-purpose tool)+ 'crawleeScraper': 'web_scraper',}DEFAULT_TOOL_DESCRIPTIONS = {'calculatorTool': 'Perform mathematical calculations. Operations: add, subtract, multiply, divide, power, sqrt, mod, abs',@@ -2562,6 +2564,8 @@ class AIService:'proxyRequest': 'Make HTTP requests through residential proxy providers with geo-targeting, session control, and automatic failover. Supports GET, POST, PUT, DELETE, PATCH methods.','proxyConfig': 'Manage proxy providers and routing rules. Operations: list_providers, add_provider, update_provider, remove_provider, set_credentials, test_provider, get_stats, add_routing_rule, list_routing_rules, remove_routing_rule.','proxyStatus': 'Get proxy provider health stats, scores, and usage statistics. Returns enabled status, provider list with health scores, and aggregated stats.',+ # Crawlee web scraping (dual-purpose tool)+ 'crawleeScraper': 'Scrape web pages to extract text, links, and structured data. Supports static HTML (beautifulsoup) and JavaScript-rendered pages (playwright). Use crawlerType to select engine.',}try:@@ -3403,6 +3407,24 @@ class AIService:return ApifyActorSchema+ # Crawlee web scraper tool schema (dual-purpose: workflow node + AI tool)+ if node_type == 'crawleeScraper':+ class CrawleeScraperSchema(BaseModel):+ """Scrape web pages to extract text, links, and structured data.+ Supports static HTML (beautifulsoup) and JS-rendered pages (playwright)."""+ url: str = Field(description="URL to scrape (https://...)")+ crawlerType: str = Field(+ default="beautifulsoup",+ description="Engine: beautifulsoup (static HTML, fast), playwright (JS-rendered), adaptive (auto-detect)"+ )+ mode: str = Field(default="single", description="single (one page) or crawl (follow links)")+ cssSelector: Optional[str] = Field(default=None, description="CSS selector to extract specific content")+ maxPages: int = Field(default=10, description="Max pages for crawl mode (1-1000)")+ outputFormat: str = Field(default="text", description="Output: text, html, or markdown")+ useProxy: bool = Field(default=False, description="Route through configured proxy")++ return CrawleeScraperSchema+# Proxy Request tool schema (dual-purpose: workflow node + AI tool)if node_type == 'proxyRequest':class ProxyRequestSchema(BaseModel):diff --git a/server/services/handlers/__init__.py b/server/services/handlers/__init__.pyindex c7850ad7..fea79f51 100644--- a/server/services/handlers/__init__.py+++ b/server/services/handlers/__init__.py@@ -111,6 +111,9 @@ from .search import (handle_perplexity_search,)+# Crawlee web scraping handler+from .crawlee import handle_crawlee_scraper+# Tool execution handlers (for AI Agent tool calling)from .tools import (execute_tool,@@ -176,6 +179,8 @@ __all__ = ['handle_brave_search','handle_serper_search','handle_perplexity_search',+ # Crawlee+ 'handle_crawlee_scraper',# Tools'execute_tool','handle_task_manager',diff --git a/server/services/handlers/crawlee.py b/server/services/handlers/crawlee.pynew file mode 100644index 00000000..103b8ecf--- /dev/null+++ b/server/services/handlers/crawlee.py@@ -0,0 +1,320 @@+"""Crawlee web scraping handler using the crawlee library.++Thin wrapper around Crawlee's BeautifulSoupCrawler and PlaywrightCrawler.+The library handles concurrency, retries, storage, and anti-bot internally.+"""++import asyncio+import time+from datetime import timedelta+from typing import Any, Dict, List, Optional++from core.logging import get_logger++logger = get_logger(__name__)++# Max content size per page to prevent memory issues+_MAX_CONTENT_LENGTH = 100_000+++async def _get_proxy_config(parameters: Dict[str, Any], url: str):+ """Bridge MachinaOs ProxyService to Crawlee ProxyConfiguration.++ Returns a crawlee.ProxyConfiguration or None.+ """+ if not parameters.get('useProxy', False):+ return None++ try:+ from services.proxy import get_proxy_service+ proxy_svc = get_proxy_service()+ proxy_url = await proxy_svc.get_proxy_url(url, parameters)+ if not proxy_url:+ return None++ from crawlee.proxy_configuration import ProxyConfiguration+ return ProxyConfiguration(proxy_urls=[proxy_url])+ except Exception as e:+ logger.warning(f"[Crawlee] Proxy setup failed, proceeding without: {e}")+ return None+++def _extract_text(soup, css_selector: str, output_format: str) -> str:+ """Extract content from BeautifulSoup object."""+ target = soup.select(css_selector) if css_selector else [soup]++ if output_format == 'html':+ parts = [str(el) for el in target]+ else:+ parts = [el.get_text(separator='\n', strip=True) for el in target]++ text = '\n\n'.join(parts)++ if output_format == 'markdown':+ try:+ import html2text+ h = html2text.HTML2Text()+ h.ignore_links = False+ h.ignore_images = False+ h.body_width = 0+ raw_html = '\n\n'.join(str(el) for el in target)+ text = h.handle(raw_html)+ except ImportError:+ pass # Fall back to plain text++ return text[:_MAX_CONTENT_LENGTH]+++def _extract_links(soup, base_url: str) -> List[str]:+ """Extract all links from page."""+ from urllib.parse import urljoin+ links = []+ for a in soup.find_all('a', href=True):+ links.append(urljoin(base_url, a['href']))+ return links+++async def handle_crawlee_scraper(+ node_id: str,+ node_type: str,+ parameters: Dict[str, Any],+ context: Dict[str, Any]+) -> Dict[str, Any]:+ """Scrape web pages using Crawlee (BeautifulSoup or Playwright).++ Args:+ node_id: Node ID+ node_type: Node type ('crawleeScraper')+ parameters: Node parameters+ context: Execution context++ Returns:+ Dict with success status, scraped pages, and metadata+ """+ start_time = time.time()++ url = parameters.get('url', '').strip()+ if not url:+ return {+ "success": False,+ "error": "URL is required",+ "execution_time": time.time() - start_time+ }++ crawler_type = parameters.get('crawlerType', 'beautifulsoup')+ mode = parameters.get('mode', 'single')+ css_selector = parameters.get('cssSelector', '')+ extract_links = parameters.get('extractLinks', False)+ output_format = parameters.get('outputFormat', 'text')+ max_pages = parameters.get('maxPages', 10) if mode == 'crawl' else 1+ max_depth = parameters.get('maxDepth', 2) if mode == 'crawl' else 0+ max_concurrency = parameters.get('maxConcurrency', 5)+ timeout_secs = parameters.get('timeout', 60)++ # Collect results from crawler handlers+ pages: List[Dict[str, Any]] = []++ try:+ proxy_config = await _get_proxy_config(parameters, url)++ if crawler_type in ('beautifulsoup', 'adaptive'):+ await _run_beautifulsoup(+ url, pages, parameters, proxy_config,+ css_selector, extract_links, output_format,+ mode, max_pages, max_depth, max_concurrency, timeout_secs,+ )+ elif crawler_type == 'playwright':+ await _run_playwright(+ url, pages, parameters, proxy_config,+ css_selector, extract_links, output_format,+ mode, max_pages, max_depth, max_concurrency, timeout_secs,+ )+ else:+ return {+ "success": False,+ "error": f"Unknown crawler type: {crawler_type}",+ "execution_time": time.time() - start_time+ }++ logger.info(f"[Crawlee] Scraped {len(pages)} page(s) from {url}")++ return {+ "success": True,+ "result": {+ "pages": pages,+ "page_count": len(pages),+ "crawler_type": crawler_type,+ "mode": mode,+ "proxied": proxy_config is not None,+ },+ "execution_time": time.time() - start_time+ }++ except ImportError as e:+ msg = str(e)+ if 'playwright' in msg.lower():+ msg = ("Playwright not installed. Run: pip install 'crawlee[playwright]' && playwright install chromium")+ elif 'crawlee' in msg.lower():+ msg = ("Crawlee not installed. Run: pip install 'crawlee[beautifulsoup]'")+ return {+ "success": False,+ "error": msg,+ "execution_time": time.time() - start_time+ }+ except Exception as e:+ logger.error(f"[Crawlee] Error scraping {url}: {e}")+ return {+ "success": False,+ "error": str(e),+ "execution_time": time.time() - start_time+ }+++async def _run_beautifulsoup(+ url: str,+ pages: List[Dict],+ parameters: Dict[str, Any],+ proxy_config,+ css_selector: str,+ extract_links: bool,+ output_format: str,+ mode: str,+ max_pages: int,+ max_depth: int,+ max_concurrency: int,+ timeout_secs: int,+) -> None:+ """Run BeautifulSoupCrawler and collect results into pages list."""+ from crawlee import ConcurrencySettings+ from crawlee.crawlers import BeautifulSoupCrawler, BeautifulSoupCrawlingContext++ crawler_kwargs: Dict[str, Any] = {+ 'max_requests_per_crawl': max_pages,+ 'max_crawl_depth': max_depth if mode == 'crawl' else 0,+ 'request_handler_timeout': timedelta(seconds=timeout_secs),+ 'concurrency_settings': ConcurrencySettings(max_concurrency=max_concurrency),+ 'configure_logging': False,+ }+ if proxy_config:+ crawler_kwargs['proxy_configuration'] = proxy_config++ crawler = BeautifulSoupCrawler(**crawler_kwargs)++ link_selector = parameters.get('linkSelector', '') or 'a[href]'+ url_pattern = parameters.get('urlPattern', '')++ @crawler.router.default_handler+ async def handler(ctx: BeautifulSoupCrawlingContext) -> None:+ title = ctx.soup.title.string if ctx.soup.title else ''+ content = _extract_text(ctx.soup, css_selector, output_format)++ page_data: Dict[str, Any] = {+ 'url': ctx.request.url,+ 'title': title,+ 'content': content,+ }+ if extract_links:+ page_data['links'] = _extract_links(ctx.soup, ctx.request.url)++ pages.append(page_data)++ # Follow links in crawl mode+ if mode == 'crawl':+ enqueue_kwargs: Dict[str, Any] = {'selector': link_selector}+ if url_pattern:+ import re+ from fnmatch import translate+ pattern = re.compile(translate(url_pattern))+ enqueue_kwargs['include'] = [pattern]+ await ctx.enqueue_links(**enqueue_kwargs)++ await asyncio.wait_for(+ crawler.run([url]),+ timeout=timeout_secs,+ )+++async def _run_playwright(+ url: str,+ pages: List[Dict],+ parameters: Dict[str, Any],+ proxy_config,+ css_selector: str,+ extract_links: bool,+ output_format: str,+ mode: str,+ max_pages: int,+ max_depth: int,+ max_concurrency: int,+ timeout_secs: int,+) -> None:+ """Run PlaywrightCrawler and collect results into pages list."""+ from crawlee import ConcurrencySettings+ from crawlee.crawlers import PlaywrightCrawler, PlaywrightCrawlingContext++ browser_type = parameters.get('browserType', 'chromium')+ wait_for_selector = parameters.get('waitForSelector', '')+ wait_timeout = parameters.get('waitTimeout', 30000)+ take_screenshot = parameters.get('screenshot', False)++ crawler_kwargs: Dict[str, Any] = {+ 'max_requests_per_crawl': max_pages,+ 'max_crawl_depth': max_depth if mode == 'crawl' else 0,+ 'request_handler_timeout': timedelta(seconds=timeout_secs),+ 'concurrency_settings': ConcurrencySettings(max_concurrency=max_concurrency),+ 'browser_type': browser_type,+ 'headless': True,+ 'configure_logging': False,+ }+ if proxy_config:+ crawler_kwargs['proxy_configuration'] = proxy_config++ crawler = PlaywrightCrawler(**crawler_kwargs)++ link_selector = parameters.get('linkSelector', '') or 'a[href]'+ url_pattern = parameters.get('urlPattern', '')++ @crawler.router.default_handler+ async def handler(ctx: PlaywrightCrawlingContext) -> None:+ page = ctx.page++ # Wait for specific element if configured+ if wait_for_selector:+ await page.wait_for_selector(wait_for_selector, timeout=wait_timeout)++ title = await page.title()++ # Get page content for extraction+ html = await page.content()+ from bs4 import BeautifulSoup+ soup = BeautifulSoup(html, 'html.parser')+ content = _extract_text(soup, css_selector, output_format)++ page_data: Dict[str, Any] = {+ 'url': ctx.request.url,+ 'title': title,+ 'content': content,+ }+ if extract_links:+ page_data['links'] = _extract_links(soup, ctx.request.url)+ if take_screenshot:+ screenshot_bytes = await page.screenshot(type='png')+ import base64+ page_data['screenshot'] = base64.b64encode(screenshot_bytes).decode()++ pages.append(page_data)++ # Follow links in crawl mode+ if mode == 'crawl':+ enqueue_kwargs: Dict[str, Any] = {'selector': link_selector}+ if url_pattern:+ import re+ from fnmatch import translate+ pattern = re.compile(translate(url_pattern))+ enqueue_kwargs['include'] = [pattern]+ await ctx.enqueue_links(**enqueue_kwargs)++ await asyncio.wait_for(+ crawler.run([url]),+ timeout=timeout_secs,+ )diff --git a/server/services/handlers/tools.py b/server/services/handlers/tools.pyindex 5e0ff7f6..38f93767 100644--- a/server/services/handlers/tools.py+++ b/server/services/handlers/tools.py@@ -171,6 +171,10 @@ async def execute_tool(tool_name: str, tool_args: Dict[str, Any],if node_type == 'apifyActor':return await _execute_apify_actor(tool_args, config.get('parameters', {}))+ # Crawlee web scraper (dual-purpose: workflow node + AI tool)+ if node_type == 'crawleeScraper':+ return await _execute_crawlee_scraper(tool_args, config.get('parameters', {}))+# Proxy nodes (dual-purpose: workflow node + AI tool)if node_type == 'proxyRequest':return await _execute_proxy_request(tool_args, config.get('parameters', {}), config)@@ -1384,6 +1388,33 @@ async def _execute_apify_actor(args: Dict[str, Any],)+async def _execute_crawlee_scraper(args: Dict[str, Any],+ node_params: Dict[str, Any]) -> Dict[str, Any]:+ """Execute Crawlee web scraper as an AI tool.++ Maps LLM-provided arguments to node parameters and delegates to handler.+ """+ from services.handlers.crawlee import handle_crawlee_scraper++ parameters = {+ **node_params,+ 'url': args.get('url', node_params.get('url', '')),+ 'crawlerType': args.get('crawlerType', node_params.get('crawlerType', 'beautifulsoup')),+ 'mode': args.get('mode', node_params.get('mode', 'single')),+ 'cssSelector': args.get('cssSelector', node_params.get('cssSelector', '')),+ 'maxPages': args.get('maxPages', node_params.get('maxPages', 10)),+ 'outputFormat': args.get('outputFormat', node_params.get('outputFormat', 'text')),+ 'useProxy': args.get('useProxy', node_params.get('useProxy', False)),+ }++ return await handle_crawlee_scraper(+ node_id="tool_crawlee_scraper",+ node_type="crawleeScraper",+ parameters=parameters,+ context={}+ )++async def _execute_proxy_request(args: Dict[str, Any],node_params: Dict[str, Any],config: Dict[str, Any]) -> Dict[str, Any]:diff --git a/server/services/node_executor.py b/server/services/node_executor.pyindex d8cd2ed3..d679f58e 100644--- a/server/services/node_executor.py+++ b/server/services/node_executor.py@@ -41,6 +41,7 @@ from services.handlers import ()from services.handlers.telegram import handle_telegram_send, handle_telegram_receivefrom services.handlers.apify import handle_apify_actor+from services.handlers.crawlee import handle_crawlee_scraperfrom services.handlers.proxy import handle_proxy_request, handle_proxy_status, handle_proxy_config# Consolidated Google Workspace handlers (6 services with operation dispatchers)from services.handlers.gmail import handle_google_gmail, handle_gmail_receive@@ -186,6 +187,8 @@ class NodeExecutor:'teamMonitor': handle_team_monitor,# Apify web scraping'apifyActor': handle_apify_actor,+ # Crawlee web scraping+ 'crawleeScraper': handle_crawlee_scraper,# Proxy nodes'proxyRequest': handle_proxy_request,'proxyStatus': handle_proxy_status,diff --git a/server/skills/web_agent/crawlee-scraper-skill/SKILL.md b/server/skills/web_agent/crawlee-scraper-skill/SKILL.mdnew file mode 100644index 00000000..d86639fb--- /dev/null+++ b/server/skills/web_agent/crawlee-scraper-skill/SKILL.md@@ -0,0 +1,132 @@+---+name: crawlee-scraper-skill+description: Scrape web pages using Crawlee. Supports static HTML (BeautifulSoup) and JavaScript-rendered content (Playwright) with proxy support.+allowed-tools: web_scraper+metadata:+ author: machina+ version: "1.0"+ category: web+ icon: "🕷"+ color: "#00D1B2"+---++# Crawlee Web Scraper Skill++Scrape web pages to extract text content, links, and structured data. Uses the Crawlee library with BeautifulSoup for static pages and Playwright for JavaScript-rendered content.++## How It Works++Connect the **Web Scraper** node to an agent's `input-tools` handle.++## web_scraper Tool++### Schema Fields++| Field | Type | Required | Description |+|-------|------|----------|-------------|+| url | string | Yes | URL to scrape (https://...) |+| crawlerType | string | No | `beautifulsoup` (static, fast), `playwright` (JS-rendered), `adaptive` (auto) |+| mode | string | No | `single` (one page) or `crawl` (follow links) |+| cssSelector | string | No | CSS selector to extract specific content |+| maxPages | integer | No | Max pages for crawl mode (default: 10) |+| outputFormat | string | No | `text`, `html`, or `markdown` |+| useProxy | boolean | No | Route through configured proxy |++### When to Use Each Crawler Type++| Type | Use Case | Speed |+|------|----------|-------|+| `beautifulsoup` | Static HTML pages, blogs, documentation, news articles | Fast |+| `playwright` | SPAs, React/Vue apps, pages with lazy-loaded content | Slower |+| `adaptive` | Unknown pages, auto-detects if JS rendering needed | Medium |++### Response Format++```json+{+ "pages": [+ {+ "url": "https://example.com",+ "title": "Example Page",+ "content": "Extracted text content...",+ "links": ["https://example.com/page2"],+ "screenshot": "base64-encoded-png (playwright only)"+ }+ ],+ "page_count": 1,+ "crawler_type": "beautifulsoup",+ "mode": "single",+ "proxied": false+}+```++### Examples++**Scrape a single page:**+```json+{+ "url": "https://example.com/article",+ "crawlerType": "beautifulsoup",+ "outputFormat": "text"+}+```++**Scrape a JS-rendered SPA:**+```json+{+ "url": "https://app.example.com/dashboard",+ "crawlerType": "playwright"+}+```++**Crawl documentation site:**+```json+{+ "url": "https://docs.example.com",+ "mode": "crawl",+ "maxPages": 50,+ "outputFormat": "markdown"+}+```++**Extract specific content with CSS selector:**+```json+{+ "url": "https://blog.example.com",+ "cssSelector": "article .post-content",+ "outputFormat": "text"+}+```++**Scrape through proxy:**+```json+{+ "url": "https://example.com",+ "useProxy": true,+ "crawlerType": "beautifulsoup"+}+```++## Guidelines++1. **Start with beautifulsoup** - it is much faster. Only use playwright when content is JS-rendered.+2. **Use CSS selectors** to extract specific content instead of scraping entire pages.+3. **Set reasonable maxPages** when crawling to avoid excessive scraping.+4. **Use proxy** for sites that rate-limit or geo-restrict.+5. **Respect robots.txt** and website terms of service.++## Error Handling++| Error | Cause | Fix |+|-------|-------|-----|+| "Crawlee not installed" | Missing dependency | `pip install 'crawlee[beautifulsoup]'` |+| "Playwright not installed" | Missing browser | `pip install 'crawlee[playwright]' && playwright install chromium` |+| Timeout | Page too slow or too many pages | Reduce maxPages or increase timeout |+| Empty content | Wrong CSS selector or JS-only page | Try playwright or adjust cssSelector |++## Setup++1. Connect **Web Scraper** node to agent's `input-tools` handle+2. BeautifulSoup works immediately (no extra setup)+3. For Playwright: `pip install 'crawlee[playwright]' && playwright install chromium`+4. For proxy: Configure proxy providers in Credentials Modal