mcpField
W
Web Scraping with Anthropic’s MCP

Web Scraping with Anthropic’s MCP

本地服务
github.com/luminati-io浏览器自动化578 周前更新

关于 Web Scraping with Anthropic’s MCP

这是一份介绍使用 Anthropic MCP 构建网页抓取服务的指南,面向希望让 Claude 等 LLM 获取实时网页数据的开发者。内容涵盖 Amazon 页面抓取示例、服务连接和 Bright Data 集成。

主要功能

  1. 01介绍 MCP 架构与工作方式
  2. 02示范构建 Python 抓取服务
  3. 03使用 Playwright 加载网页
  4. 04通过 LXML 和 XPath 提取信息
  5. 05说明连接 Claude Desktop 与 Cursor

适用场景

  1. 01抓取 Amazon 商品页面信息
  2. 02让 LLM 获取实时网页数据
  3. 03配置 MCP 客户端调用抓取工具

MCP 相关

指南示范构建 MCP 服务,以 `fetch_page` 和 `extract_info` 工具抓取并解析网页,并通过 STDIO 连接 Claude Desktop 或 Cursor。也介绍了 Bright Data 的网页数据提取服务。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

使用 Anthropic 的 MCP 进行网页抓取

Bright Data 促销

本指南将介绍如何设置 MCP 服务以按需提取数据、连接开发工具,并利用 Bright Data 即时获取兼容 AI 的网页信息。

了解限制:为什么大模型需要借助工具与现实世界交互

大语言模型(LLM)擅长处理和生成基于海量训练数据的文本。然而,它们面临一项关键限制——无法自然地与外部世界交互。这意味着它们没有内置能力来访问本地文件、执行自定义脚本或从网站获取最新信息。

举个简单的例子:如果没有额外工具,让 Claude 从正在运营的 Amazon 商品页面提取详细信息是不可能的。为什么?因为它本身不具备浏览互联网或触发外部操作的能力。

claude-without-mcp

没有辅助工具,大模型就无法执行依赖实时数据或与外部系统集成的实用任务。

这正是 Anthropic 的模型上下文协议(MCP)发挥作用的地方。它让大模型能够以安全、标准化的方式与外部工具(例如数据提取器、API 或脚本)通信。

以下是实际效果。集成自定义 MCP 服务后,我们成功地通过 Claude 直接提取了结构化的 Amazon 商品信息:

claude-amazon-product-data-extraction-results

MCP 的重要性

  • **标准化:**MCP 为基于大模型的系统提供统一接口,以连接外部工具和数据——类似于 API 标准化 Web 集成的方式。这大幅减少了对自定义集成的需求,加快了开发速度。
  • **灵活性与可扩展性:**开发者可以更换大模型或托管平台,而无需重写工具集成。MCP 支持多种通信方式(例如 stdio),因此可以适应各种配置。
  • **增强大模型能力:**通过将大模型连接到最新数据和外部工具,MCP 使其不再局限于静态回复。它们现在可以提供最新、相关的信息,并根据上下文触发真实世界中的操作。

类比:

可以把 MCP 看作是大模型的 USB 接口。就像 USB 让不同设备(键盘、打印机、外置硬盘)无需特殊驱动即可连接到任何兼容设备,MCP 也让大模型能够通过标准化协议连接各种工具——每次都无需自定义集成。

了解 Model Context Protocol

Model Context Protocol(MCP)是由 Anthropic 开发的开放标准,可让大模型(LLM)以一致、安全的方式与外部工具、API 和数据源交互。它充当通用连接器,让大模型能够执行提取网站数据、查询数据库或运行脚本等现实任务。

MCP 由 Anthropic 推出,但它是开放且可扩展的,这意味着任何人都可以实现或参与该标准。如果你曾使用过 检索增强生成(RAG),就会理解这个概念。MCP 在此基础上,通过轻量级 JSON-RPC 接口标准化交互,让模型能够访问实时数据并采取行动。

MCP 架构详解

MCP 的核心是标准化 AI 模型与外部能力之间的通信。

核心理念: 通过标准化接口(通常使用 stdio 等传输方式上的 JSON-RPC 2.0),大模型(通过客户端)可以发现并调用外部服务所提供的工具。

MCP 采用客户端-服务架构,包含三个关键组件:

  1. MCP 主机:发起并管理大模型与外部工具交互的环境或应用。示例包括 Claude Desktop 等 AI 助手,或 Cursor 等 IDE。
  2. MCP 客户端:主机中的一个组件,用于与 MCP 服务建立并维持连接,处理通信协议并管理数据交换。
  3. MCP 服务端: 一个实现 MCP 协议并提供特定能力的程序(由开发者创建)。MCP 服务可以连接数据库、Web 服务,或在本例中连接网站(Amazon)。服务以标准化方式提供其功能:
    • 工具: 可调用的函数(例如 scrape_amazon_product、get_weather_data)
    • 资源: 用于检索静态数据的只读端点(例如获取文件、返回 JSON 记录)
    • 提示词: 用于引导大模型与工具和资源交互的预定义模板

以下是 MCP 架构图:

mcp-architecture-diagram-host-client-server-connections

图片来源:Model Context Protocol

在此设置中,主机(Claude Desktop 或 Cursor IDE)会启动一个 MCP 客户端,再由该客户端连接到外部 MCP 服务。该服务提供工具、资源和提示词,以便 AI 按需与之交互。

简而言之,工作流如下:

  • 用户发送一条消息,例如 “从这个 Amazon 链接提取商品信息。”
  • MCP 客户端检查是否有已注册的工具可以处理该任务
  • 客户端向 MCP 服务发送结构化请求
  • MCP 服务执行相应操作(例如启动无头浏览器)
  • 服务向 MCP 客户端返回结构化结果
  • 客户端将结果转发给大模型,由大模型呈现给用户

开发自己的 MCP 服务

让我们构建一个 Python MCP 服务,从 Amazon 商品页面提取数据。

amazon-product-page-example

此服务将提供两个工具:一个用于下载 HTML,另一个用于提取整理后的信息。你将通过 Cursor 或 Claude Desktop 中的大模型客户端与该服务交互。

步骤 1:准备环境

首先,确认已安装 Python 3。然后,创建并激活虚拟环境:

python -m venv mcp-amazon-scraper
# On macOS/Linux:
source mcp-amazon-scraper/bin/activate
# On Windows:
.\mcp-amazon-scraper\Scripts\activate

安装所需的库:MCP Python SDK、Playwright 和 LXML。

pip install mcp playwright lxml
# Install browser binaries for Playwright
python -m playwright install

这会安装:

  • mcp:用于 Model Context Protocol 服务和客户端的 Python SDK,负责处理所有 JSON-RPC 通信细节
  • playwright:浏览器自动化库,提供无头浏览器功能,可渲染和抓取包含大量 JavaScript 的网站
  • lxml:快速的 XML/HTML 解析库,可使用 XPath 查询轻松提取网页中的特定数据元素

简而言之,MCP Python SDK(mcp)负责处理所有协议细节,让你能够公开工具,供 Claude 或 Cursor 通过自然语言提示词调用。Playwright 可完整渲染网页(包括 JavaScript 内容),而 lxml 则提供强大的 HTML 解析能力。

步骤 2:启动 MCP 服务

创建一个名为 amazon_scraper_mcp.py 的 Python 文件。首先导入所需模块并初始化 FastMCP 服务:

import os
import asyncio
from lxml import html as lxml_html
from mcp.server.fastmcp import FastMCP
from playwright.async_api import async_playwright

# Define a temporary file path for the HTML content
HTML_FILE = os.path.join(os.getenv("TMPDIR", "/tmp"), "amazon_product_page.html")

# Initialize the MCP server with a descriptive name
mcp = FastMCP("Amazon Product Scraper")

print("MCP Server Initialized: Amazon Product Scraper")

这会创建一个 MCP 服务实例。接下来,我们将在其中添加工具。

步骤 3:实现 fetch_page 工具

此工具将接收一个 URL 作为输入,使用 Playwright 导航到该页面,等待内容加载,下载 HTML,并将其保存到临时文件中。

@mcp.tool()
async def fetch_page(url: str) -> str:
    """
    Fetches the HTML content of the given Amazon product URL using Playwright
    and saves it to a temporary file. Returns a status message.
    """
    print(f"Executing fetch_page for URL: {url}")
    try:
        async with async_playwright() as p:
            # Launch headless Chromium browser
            browser = await p.chromium.launch(headless=True)
            page = await browser.new_page()
            # Navigate to the URL with a generous timeout
            await page.goto(url, timeout=90000, wait_until="domcontentloaded")
            # Wait for a key element (e.g., body) to ensure basic loading
            await page.wait_for_selector("body", timeout=30000)
            # Add a small delay for any dynamic content rendering via JavaScript
            await asyncio.sleep(5)

            html_content = await page.content()
            with open(HTML_FILE, "w", encoding="utf-8") as f:
                f.write(html_content)

            await browser.close()
            print(f"Successfully fetched and saved HTML to {HTML_FILE}")
            return f"HTML content for {url} downloaded and saved successfully to {HTML_FILE}."
    except Exception as e:
        error_message = f"Error fetching page {url}: {str(e)}"
        print(error_message)
        return error_message

这个异步函数使用 Playwright 处理 Amazon 页面可能涉及的 JavaScript 渲染。@mcp.tool() 装饰器会将此函数注册为服务中可调用的工具。

步骤 4:实现 extract_info 工具

此工具会读取 fetch_page 保存的 HTML 文件,使用 LXML 和 XPath 选择器进行解析,并返回一个包含所提取产品详情的字典。

def _extract_xpath(tree, xpath, default="N/A"):
    """Helper function to extract text using XPath, returning default if not found."""
    try:
        # Use text_content() to get text from node and children, strip whitespace
        result = tree.xpath(xpath)
        if result:
            return result[0].text_content().strip()
        return default
    except Exception:
        return default

def _extract_price(price_str):
    """Helper function to parse price string into a float."""
    if price_str == "N/A":
        return None
    try:
        # Remove currency symbols and commas, handle potential whitespace
        cleaned_price = "".join(filter(str.isdigit or str.__eq__("."), price_str))
        return float(cleaned_price)
    except (ValueError, TypeError):
        return None

@mcp.tool()
def extract_info() -> dict:
    """
    Parses the saved HTML file (downloaded by fetch_page) to extract
    Amazon product details like title, price, rating, features, etc.
    Returns a dictionary of the extracted data.
    """
    print(f"Executing extract_info from file: {HTML_FILE}")
    if not os.path.exists(HTML_FILE):
        return {
            "error": f"HTML file not found at {HTML_FILE}. Please run fetch_page first."
        }

    try:
        with open(HTML_FILE, "r", encoding="utf-8") as f:
            page_html = f.read()

        tree = lxml_html.fromstring(page_html)

        # --- XPath Selectors for Amazon Product Details ---
        title = _extract_xpath(tree, '//span[@id="productTitle"]')
        # Handle different price structures (main price, sale price)
        price_whole = _extract_xpath(tree, '//span[contains(@class, "a-price-whole")]')
        price_fraction = _extract_xpath(
            tree, '//span[contains(@class, "a-price-fraction")]'
        )
        price_str = (
            f"{price_whole}.{price_fraction}"
            if price_whole != "N/A"
            else _extract_xpath(tree, '//span[contains(@class,"a-offscreen")]')
        )  # Fallback to offscreen if needed

        price = _extract_price(price_str)

        # Original price (strike-through)
        original_price_str = _extract_xpath(
            tree, '//span[@class="a-price a-text-price"]//span[@class="a-offscreen"]'
        )
        original_price = _extract_price(original_price_str)

        # Rating
        rating_text = _extract_xpath(tree, '//span[@id="acrPopover"]/@title')
        rating = None
        if rating_text != "N/A":
            try:
                rating = float(rating_text.split()[0])
            except (ValueError, IndexError):
                rating = None

        # Review Count
        reviews_text = _extract_xpath(tree, '//span[@id="acrCustomerReviewText"]')
        review_count = None
        if reviews_text != "N/A":
            try:
                review_count = int(reviews_text.split()[0].replace(",", ""))
            except (ValueError, IndexError):
                review_count = None

        # Availability
        availability = _extract_xpath(
            tree,
            '//div[@id="availability"]//span/text()',
        )

        # Features (bullet points)
        feature_elements = tree.xpath(
            '//div[@id="feature-bullets"]//li//span[@class="a-list-item"]'
        )
        features = [
            elem.text_content().strip()
            for elem in feature_elements
            if elem.text_content().strip()
        ]

        # Calculate Discount
        discount = None
        if price and original_price and original_price > price:
            discount = round(((original_price - price) / original_price) * 100)

        extracted_data = {
            "title": title,
            "price": price,
            "original_price": original_price,
            "discount_percent": discount,
            "rating_stars": rating,
            "review_count": review_count,
            "features": features,
            "availability": availability.strip(),
        }
        print(f"Successfully extracted data: {extracted_data}")
        return extracted_data

    except Exception as e:
        error_message = f"Error parsing HTML: {str(e)}"
        print(error_message)  # Added for logging
        return {"error": error_message}

此函数使用 LXML 的 fromstring 解析 HTML,并通过可靠的 XPath 选择器查找所需元素

步骤 5:运行服务

最后,将以下代码行添加到 amazon_scraper_mcp.py 脚本末尾,使用 stdio 传输机制启动服务。这是本地 MCP 服务与 Claude Desktop 或 Cursor 等客户端通信时的标准方式。

if __name__ == "__main__":
    print("Starting MCP Server with stdio transport...")
    # Run the server, listening via standard input/output
    mcp.run(transport="stdio")
完整源代码
import os
import asyncio
from lxml import html as lxml_html
from mcp.server.fastmcp import FastMCP
from playwright.async_api import async_playwright

# Define a temporary file path for the HTML content
HTML_FILE = os.path.join(os.getenv("TMPDIR", "/tmp"), "amazon_product_page.html")

# Initialize the MCP server with a descriptive name
mcp = FastMCP("Amazon Product Scraper")

print("MCP Server Initialized: Amazon Product Scraper")

@mcp.tool()
async def fetch_page(url: str) -> str:
    """
    Fetches the HTML content of the given Amazon product URL using Playwright
    and saves it to a temporary file. Returns a status message.
    """
    print(f"Executing fetch_page for URL: {url}")
    try:
        async with async_playwright() as p:
            # Launch headless Chromium browser
            browser = await p.chromium.launch(headless=True)
            page = await browser.new_page()
            # Navigate to the URL with a generous timeout
            await page.goto(url, timeout=90000, wait_until="domcontentloaded")
            # Wait for a key element (e.g., body) to ensure basic loading
            await page.wait_for_selector("body", timeout=30000)
            # Add a small delay for any dynamic content rendering via JavaScript
            await asyncio.sleep(5)

            html_content = await page.content()
            with open(HTML_FILE, "w", encoding="utf-8") as f:
                f.write(html_content)

            await browser.close()
            print(f"Successfully fetched and saved HTML to {HTML_FILE}")
            return f"HTML content for {url} downloaded and saved successfully to {HTML_FILE}."
    except Exception as e:
        error_message = f"Error fetching page {url}: {str(e)}"
        print(error_message)
        return error_message

def _extract_xpath(tree, xpath, default="N/A"):
    """Helper function to extract text using XPath, returning default if not found."""
    try:
        # Use text_content() to get text from node and children, strip whitespace
        result = tree.xpath(xpath)
        if result:
            return result[0].text_content().strip()
        return default
    except Exception:
        return default

def _extract_price(price_str):
    """Helper function to parse price string into a float."""
    if price_str == "N/A":
        return None
    try:
        # Remove currency symbols and commas, handle potential whitespace
        cleaned_price = "".join(filter(str.isdigit or str.__eq__("."), price_str))
        return float(cleaned_price)
    except (ValueError, TypeError):
        return None

@mcp.tool()
def extract_info() -> dict:
    """
    Parses the saved HTML file (downloaded by fetch_page) to extract
    Amazon product details like title, price, rating, features, etc.
    Returns a dictionary of the extracted data.
    """
    print(f"Executing extract_info from file: {HTML_FILE}")
    if not os.path.exists(HTML_FILE):
        return {
            "error": f"HTML file not found at {HTML_FILE}. Please run fetch_page first."
        }

    try:
        with open(HTML_FILE, "r", encoding="utf-8") as f:
            page_html = f.read()

        tree = lxml_html.fromstring(page_html)

        # --- XPath Selectors for Amazon Product Details ---
        title = _extract_xpath(tree, '//span[@id="productTitle"]')
        # Handle different price structures (main price, sale price)
        price_whole = _extract_xpath(tree, '//span[contains(@class, "a-price-whole")]')
        price_fraction = _extract_xpath(
            tree, '//span[contains(@class, "a-price-fraction")]'
        )
        price_str = (
            f"{price_whole}.{price_fraction}"
            if price_whole != "N/A"
            else _extract_xpath(tree, '//span[contains(@class,"a-offscreen")]')
        )  # Fallback to offscreen if needed

        price = _extract_price(price_str)

        # Original price (strike-through)
        original_price_str = _extract_xpath(
            tree, '//span[@class="a-price a-text-price"]//span[@class="a-offscreen"]'
        )
        original_price = _extract_price(original_price_str)

        # Rating
        rating_text = _extract_xpath(tree, '//span[@id="acrPopover"]/@title')
        rating = None
        if rating_text != "N/A":
            try:
                rating = float(rating_text.split()[0])
            except (ValueError, IndexError):
                rating = None

        # Review Count
        reviews_text = _extract_xpath(tree, '//span[@id="acrCustomerReviewText"]')
        review_count = None
        if reviews_text != "N/A":
            try:
                review_count = int(reviews_text.split()[0].replace(",", ""))
            except (ValueError, IndexError):
                review_count = None

        # Availability
        availability = _extract_xpath(
            tree,
            '//div[@id="availability"]//span/text()',
        )

        # Features (bullet points)
        feature_elements = tree.xpath(
            '//div[@id="feature-bullets"]//li//span[@class="a-list-item"]'
        )
        features = [
            elem.text_content().strip()
            for elem in feature_elements
            if elem.text_content().strip()
        ]

        # Calculate Discount
        discount = None
        if price and original_price and original_price > price:
            discount = round(((original_price - price) / original_price) * 100)

        extracted_data = {
            "title": title,
            "price": price,
            "original_price": original_price,
            "discount_percent": discount,
            "rating_stars": rating,
            "review_count": review_count,
            "features": features,
            "availability": availability.strip(),
        }
        print(f"Successfully extracted data: {extracted_data}")
        return extracted_data

    except Exception as e:
        error_message = f"Error parsing HTML: {str(e)}"
        print(error_message)  # Added for logging
        return {"error": error_message}

if __name__ == "__main__":
    print("Starting MCP Server with stdio transport...")
    # Run the server, listening via standard input/output
    mcp.run(transport="stdio")

连接 MCP 服务

现在服务脚本已准备就绪,接下来将它连接到 Claude Desktop 和 Cursor 等 MCP 客户端。

使用 Claude Desktop 进行设置

步骤 1: 打开 Claude Desktop。

步骤 2: 前往 Settings -> Developer -> Edit Config。这将使用默认文本编辑器打开 claude_desktop_config.json 文件。

Claude Desktop 设置菜单导航

步骤 3: 在 mcpServers 键下为你的服务添加一项。请务必将 args 中的路径替换为 amazon_scraper_mcp.py 文件的绝对路径。

{
  "mcpServers": {
    "amazon_product_scraper": {
      "command": "python",  // Or python3 if needed
      "args": ["/full/path/to/your/amazon_scraper_mcp.py"], // <-- IMPORTANT: Use the correct absolute path
    }
  }
}

步骤 4: 保存 claude_desktop_config.json 文件,然后完全退出并重新打开 Claude Desktop,使更改生效。

步骤 5: 现在,你应该可以在 Claude Desktop 的聊天输入区域看到一个小工具图标(类似锤子 🔨)。

Claude Desktop MCP 工具图标界面

步骤 6: 点击该图标后,应会列出“Amazon Product Scraper”及其 fetch_page 和 extract_info 工具。

Claude 可用 MCP 工具对话框:Amazon Scraper

步骤 7: 发送提示词,例如:“获取此 Amazon 商品的当前价格、原价和评分:https://www.amazon.com/dp/B09C13PZX7”。

步骤 8: Claude 会检测到这需要使用外部工具,并提示你授权先运行 fetch_page,然后运行 extract_info。对每个工具点击“Allow for this chat”。

MCP 权限对话框:Amazon 工具的 fetch_page

步骤 9: 授予权限后,MCP 服务将执行这些工具。随后 Claude 会接收结构化数据,并在聊天中展示。

Claude Amazon 商品数据提取结果

使用 Cursor 进行设置

Cursor(一款 AI 优先的 IDE)的设置流程类似。

步骤 1: 打开 Cursor。

步骤 2: 进入 Settings ⚙️,然后转到 MCP 部分。

cursor-ide-add-new-global-mcp-server-settings

步骤 3: 点击“+Add a new global MCP Server”。这将打开 mcp.json 配置文件。为你的服务添加一条配置,同样使用脚本的绝对路径。

cursor-mcp-json-configuration-file-amazon-scraper

步骤 4: 保存 mcp.json 文件,你应该会看到列出的“amazon_product_scraper”,希望它旁边有一个绿点,表示它正在运行并已连接。

cursor-ide-configured-amazon-scraper-mcp-settings

步骤 5: 使用 Cursor 的聊天功能(Cmd+l 或 Ctrl+l)。

步骤 6: 发送提示词,例如:“从此 Amazon URL 提取所有可用的产品数据:https://www.amazon.com/dp/B09C13PZX7。将输出格式化为结构化的 JSON 对象”。

步骤 7: 与 Claude Desktop 类似,Cursor 会请求你允许运行 fetch_page 和 extract_info 工具。批准这些请求(“Run Tool”)。

步骤 8: Cursor 会显示交互流程,展示对 MCP 工具的调用,最后呈现 extract_info 工具返回的结构化 JSON 数据。

cursor-ide-amazon-product-data-extraction-json-results 以下是 Cursor 输出的 JSON 示例:

{
  "title": "Razer Basilisk V3 Customizable Ergonomic Gaming Mouse: Fastest Gaming Mouse Switch - Chroma RGB Lighting - 26K DPI Optical Sensor - 11 Programmable Buttons - HyperScroll Tilt Wheel - Classic Black",
  "price": 39.99,
  "original_price": 69.99,
  "discount_percent": 43,
  "rating_stars": 4.6,
  "review_count": 7782,
  "features": [
    "ICONIC ERGONOMIC DESIGN WITH THUMB REST — PC gaming mouse favored by millions worldwide with a form factor that perfectly supports the hand while its buttons are optimally positioned for quick and easy access",
    "11 PROGRAMMABLE BUTTONS — Assign macros and secondary functions across 11 programmable buttons to execute essential actions like push-to-talk, ping, and more",
    "HYPERSCROLL TILT WHEEL — Speed through content with a scroll wheel that free-spins until its stopped or switch to tactile mode for more precision and satisfying feedback that's ideal for cycling through weapons or skills",
    "11 RAZER CHROMA RGB LIGHTING ZONES — Customize each zone from over 16.8 million colors and countless lighting effects, all while it reacts dynamically with over 150 Chroma integrated games",
    "OPTICAL MOUSE SWITCHES GEN 2 — With zero unintended misclicks these switches provide crisp, responsive execution at a blistering 0.2ms actuation speed for up to 70 million clicks",
    "FOCUS+ 26K DPI OPTICAL SENSOR — Best-in-class mouse sensor with intelligent functions flawlessly tracks movement with zero smoothing, allowing for crisp response and pixel-precise accuracy",
    // ... (other features)
  ],
  "availability": "In Stock"
}

这展示了 MCP 的灵活性——同一服务可以与不同的客户端应用无缝协作。

使用 Bright Data 的 MCP 进行专业网页数据提取

Bright Data 的企业级 Model Context Protocol (MCP) 解决方案消除了自主管理 MCP 服务的复杂性——例如代理管理、反机器人导航和扩展方面的挑战——并可与 AI Agent 和大模型无缝集成。

连接到 Bright Data 的 MCP,即可立即访问公开网页数据,包括 SERP 结果和难以访问的网站,并针对 AI 工作流进行优化。

MCP 借助 Web Unlocker、SERP API、Web Scraper API 和 Scraping Browser 等工具,构建强大的网页提取框架,提供:

  • 适用于 AI 的数据: 预先结构化的内容,无需预处理。
  • 可扩展性与可靠性: 支持高容量运行,不会出现速度下降。
  • 绕过封锁与 CAPTCHA: 先进的反机器人能力。
  • 全球 IP 覆盖: 通过 Bright Data 代理访问 195 个国家/地区。
  • 无缝集成: 可快速接入任何 MCP 客户端。
Bright Data MCP 的前置条件

开始集成 Bright Data MCP 前,请确认你具备以下条件:

  1. Bright Data 账户: 在 brightdata.com 注册。新用户可获得免费额度用于测试。
  2. API 令牌: 在 Bright Data 账户设置中获取 API 令牌(用户设置页面)。
  3. Web Unlocker 区域: 在 Bright Data 控制面板中创建 Web Unlocker 代理区域。选择一个容易记住的标识符,例如 mcp_unlocker(如有需要,之后可通过环境变量修改)。
  4. (可选)Scraping Browser 区域: 如果需要高级浏览器自动化功能(例如复杂的 JavaScript 交互或截图),请创建 Scraping Browser 区域。记录该区域提供的身份验证信息(用户名和密码,位于 概览 标签页中),其格式通常为 brd-customer-ACCOUNT_ID-zone-ZONE_NAME:PASSWORD。
快速入门:为 Claude Desktop 配置 Bright Data MCP

步骤 1: Bright Data MCP 服务通常通过 npx 运行,该工具随 Node.js 一同安装。如有需要,请从官方网站安装 Node.js。

步骤 2: 打开 Claude Desktop -> Settings -> Developer -> Edit Config(claude_desktop_config.json)。

步骤 3: 在 mcpServers 下插入 Bright Data 服务配置。将占位符替换为你的实际凭据。

{
  "mcpServers": {
    "Bright Data": { // Choose a name for the server
      "command": "npx",
      "args": ["@brightdata/mcp"],
      "env": {
        "API_TOKEN": "YOUR_BRIGHTDATA_API_TOKEN", // Paste your API token here
        "WEB_UNLOCKER_ZONE": "mcp_unlocker",     // Your Web Unlocker zone name
        // Optional: Add if using Scraping Browser tools
        "BROWSER_AUTH": "brd-customer-ACCOUNTID-zone-YOURZONE:PASSWORD"
      }
    }
  }
}

步骤 4: 保存配置文件并重启 Claude Desktop。

步骤 5: 将鼠标悬停在 Claude Desktop 中的锤子图标(🔨)上。现在应该可以看到多个可用的 MCP 工具。

claude-desktop-interface-with-mcp-tools-available

让我们尝试从 Zillow 提取数据。该网站以可能限制爬虫而闻名。向 Claude 提示:“请以 JSON 格式,从此 Zillow URL 提取关键房产数据:https://www.zillow.com/apartments/arverne-ny/the-tides-at-arverne-by-the-sea/ChWHPZ/”

bright-data-mcp-zillow-property-extraction-process

允许 Claude 使用所需的 Bright Data MCP 工具。Bright Data 的 MCP 服务将处理底层的复杂工作(代理轮换,以及在需要时通过 Scraping Browser 渲染 JavaScript)。

Bright Data 的服务会执行提取并返回结构化数据,随后由 Claude 展示。

zillow-property-data-json-structure-bright-data-mcp

以下是可能输出的示例:

{
  "propertyInfo": {
    "name": "The Tides At Arverne By The Sea",
    "address": "190 Beach 69th St, Arverne, NY 11692",
    "propertyType": "Apartment building",
    // ... more info
  },
  "rentPrices": {
    "studio": { "startingPrice": "$2,750", /* ... */ },
    "oneBed": { "startingPrice": "$2,900", /* ... */ },
    "twoBed": { "startingPrice": "$3,350", /* ... */ }
  },
  // ... amenities, policies, etc.
}

另一个示例:Hacker News 标题

一个更简单的查询:“请列出 Hacker News 最新 5 篇新闻文章的标题”。

hacker-news-latest-articles-mcp-extraction-results

这展示了 Bright Data 的 MCP 服务如何简化在 AI 工作流中直接访问动态或安全防护严密的网页内容。

延伸阅读

以下是我们此前发布的 AI 和大语言模型(LLM)指南精选,可帮助你深入了解相关知识:

结论

Anthropic 的 Model Context Protocol 从根本上改变了 AI 系统与外部世界交互的方式。你可以针对特定任务构建自定义 MCP 服务。Bright Data 的 MCP 集成进一步增强了这一能力,提供企业级网页抓取功能,能够规避反机器人保护措施,并提供 适用于 AI 的结构化数据。

立即注册并免费试用 AI 解决方案!

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。