File size: 11,547 Bytes
09801ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
"""
Web Scraper MCP Tool - FREE
============================

A free web scraping tool that can:
1. Scrape webpage content
2. Extract structured data (tables, lists)
3. Search the web (using free DuckDuckGo)
4. Get news headlines

NO API KEYS REQUIRED - uses free public services.
"""

import os
import re
import json
import logging
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from urllib.parse import quote_plus, urljoin
import asyncio

# These are standard library + already installed packages
import requests
from bs4 import BeautifulSoup

logger = logging.getLogger(__name__)


# User agent to avoid blocks
HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}


@dataclass
class ScrapedPage:
    """Result from scraping a webpage"""
    url: str
    title: str
    text_content: str
    tables: List[Dict[str, Any]]
    links: List[Dict[str, str]]
    metadata: Dict[str, Any]


@dataclass 
class SearchResult:
    """A single search result"""
    title: str
    url: str
    snippet: str


class WebScraperMCP:
    """
    Free web scraping MCP tool.
    
    No API keys required - uses public web services.
    """
    
    def __init__(self, timeout: int = 10):
        self.timeout = timeout
        self.session = requests.Session()
        self.session.headers.update(HEADERS)
    
    def scrape_url(self, url: str) -> ScrapedPage:
        """
        Scrape content from a URL.
        
        Returns structured content including text, tables, and links.
        """
        
        try:
            response = self.session.get(url, timeout=self.timeout)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            
            # Remove script and style elements
            for element in soup(['script', 'style', 'nav', 'footer', 'header']):
                element.decompose()
            
            # Get title
            title = soup.title.string if soup.title else ""
            
            # Get main text content
            text_content = soup.get_text(separator='\n', strip=True)
            # Clean up excessive whitespace
            text_content = re.sub(r'\n{3,}', '\n\n', text_content)
            
            # Extract tables
            tables = []
            for table in soup.find_all('table')[:5]:  # Limit to 5 tables
                table_data = self._parse_table(table)
                if table_data:
                    tables.append(table_data)
            
            # Extract links
            links = []
            for a in soup.find_all('a', href=True)[:20]:  # Limit to 20 links
                href = a['href']
                if href.startswith('http'):
                    links.append({
                        "text": a.get_text(strip=True),
                        "url": href
                    })
                elif href.startswith('/'):
                    links.append({
                        "text": a.get_text(strip=True),
                        "url": urljoin(url, href)
                    })
            
            # Get metadata
            metadata = {}
            meta_desc = soup.find('meta', attrs={'name': 'description'})
            if meta_desc:
                metadata['description'] = meta_desc.get('content', '')
            
            return ScrapedPage(
                url=url,
                title=title,
                text_content=text_content[:10000],  # Limit content
                tables=tables,
                links=links,
                metadata=metadata
            )
            
        except Exception as e:
            logger.error(f"Error scraping {url}: {e}")
            return ScrapedPage(
                url=url,
                title="Error",
                text_content=f"Failed to scrape: {str(e)}",
                tables=[],
                links=[],
                metadata={"error": str(e)}
            )
    
    def _parse_table(self, table) -> Optional[Dict[str, Any]]:
        """Parse an HTML table into structured data"""
        
        try:
            rows = table.find_all('tr')
            if not rows:
                return None
            
            # Get headers
            headers = []
            header_row = rows[0].find_all(['th', 'td'])
            headers = [cell.get_text(strip=True) for cell in header_row]
            
            # Get data rows
            data = []
            for row in rows[1:10]:  # Limit rows
                cells = row.find_all(['td', 'th'])
                row_data = [cell.get_text(strip=True) for cell in cells]
                if row_data:
                    data.append(row_data)
            
            return {
                "headers": headers,
                "rows": data
            }
            
        except Exception as e:
            logger.warning(f"Error parsing table: {e}")
            return None
    
    def search_duckduckgo(
        self, 
        query: str, 
        max_results: int = 5
    ) -> List[SearchResult]:
        """
        Search the web using DuckDuckGo (FREE, no API key).
        
        Returns list of search results.
        """
        
        try:
            # DuckDuckGo HTML search
            search_url = f"https://html.duckduckgo.com/html/?q={quote_plus(query)}"
            
            response = self.session.get(search_url, timeout=self.timeout)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.text, 'html.parser')
            
            results = []
            for result in soup.find_all('div', class_='result')[:max_results]:
                title_elem = result.find('a', class_='result__a')
                snippet_elem = result.find('a', class_='result__snippet')
                
                if title_elem:
                    results.append(SearchResult(
                        title=title_elem.get_text(strip=True),
                        url=title_elem.get('href', ''),
                        snippet=snippet_elem.get_text(strip=True) if snippet_elem else ""
                    ))
            
            logger.info(f"DuckDuckGo search for '{query}': {len(results)} results")
            return results
            
        except Exception as e:
            logger.error(f"Search error: {e}")
            return []
    
    def get_news(
        self, 
        query: str = "", 
        max_results: int = 5
    ) -> List[Dict[str, str]]:
        """
        Get news headlines (FREE, using Google News RSS).
        
        Returns list of news items.
        """
        
        try:
            if query:
                # Search news
                rss_url = f"https://news.google.com/rss/search?q={quote_plus(query)}&hl=en-US&gl=US&ceid=US:en"
            else:
                # Top headlines
                rss_url = "https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en"
            
            response = self.session.get(rss_url, timeout=self.timeout)
            response.raise_for_status()
            
            soup = BeautifulSoup(response.content, 'xml')
            
            news = []
            for item in soup.find_all('item')[:max_results]:
                title = item.find('title')
                link = item.find('link')
                pub_date = item.find('pubDate')
                source = item.find('source')
                
                news.append({
                    "title": title.get_text() if title else "",
                    "url": link.get_text() if link else "",
                    "date": pub_date.get_text() if pub_date else "",
                    "source": source.get_text() if source else ""
                })
            
            logger.info(f"Got {len(news)} news items for '{query}'")
            return news
            
        except Exception as e:
            logger.error(f"News error: {e}")
            return []
    
    def extract_text_from_url(self, url: str, max_length: int = 5000) -> str:
        """
        Simple helper to get just text from a URL.
        """
        
        result = self.scrape_url(url)
        return result.text_content[:max_length]


# MCP Tool Interface
class WebMCPTool:
    """
    MCP-compatible interface for the web scraper.
    """
    
    name = "web_scraper"
    description = "Search the web, scrape webpages, and get news - FREE, no API key required"
    
    def __init__(self):
        self.scraper = WebScraperMCP()
    
    async def execute(self, action: str, params: Dict[str, Any]) -> Dict[str, Any]:
        """
        Execute a web scraping action.
        
        Actions:
        - scrape: Scrape a URL
        - search: Search the web
        - news: Get news headlines
        """
        
        try:
            if action == "scrape":
                url = params.get("url", "")
                if not url:
                    return {"error": "URL required"}
                
                result = self.scraper.scrape_url(url)
                return {
                    "title": result.title,
                    "content": result.text_content[:3000],
                    "tables": result.tables,
                    "links": result.links[:10]
                }
            
            elif action == "search":
                query = params.get("query", "")
                if not query:
                    return {"error": "Query required"}
                
                results = self.scraper.search_duckduckgo(
                    query, 
                    max_results=params.get("max_results", 5)
                )
                return {
                    "results": [
                        {"title": r.title, "url": r.url, "snippet": r.snippet}
                        for r in results
                    ]
                }
            
            elif action == "news":
                query = params.get("query", "")
                results = self.scraper.get_news(
                    query,
                    max_results=params.get("max_results", 5)
                )
                return {"news": results}
            
            else:
                return {"error": f"Unknown action: {action}"}
                
        except Exception as e:
            return {"error": str(e)}


# Convenience functions for direct use
def search_web(query: str, max_results: int = 5) -> List[Dict[str, str]]:
    """Quick web search"""
    scraper = WebScraperMCP()
    results = scraper.search_duckduckgo(query, max_results)
    return [{"title": r.title, "url": r.url, "snippet": r.snippet} for r in results]


def get_webpage_text(url: str) -> str:
    """Get text content from a URL"""
    scraper = WebScraperMCP()
    return scraper.extract_text_from_url(url)


def get_news_headlines(topic: str = "", max_results: int = 5) -> List[Dict[str, str]]:
    """Get news headlines"""
    scraper = WebScraperMCP()
    return scraper.get_news(topic, max_results)


# Test
if __name__ == "__main__":
    # Test search
    print("=== Web Search ===")
    results = search_web("artificial intelligence trends 2024")
    for r in results:
        print(f"- {r['title']}")
    
    # Test news
    print("\n=== News ===")
    news = get_news_headlines("technology")
    for n in news:
        print(f"- {n['title']} ({n['source']})")
    
    # Test scrape
    print("\n=== Scrape ===")
    text = get_webpage_text("https://example.com")
    print(text[:500])