SDKs

LangChain SDK

Use MrScraper as LangChain tools via the langchain-mrscraper package to retrieve pages as HTML, Markdown, or screenshots, extract brand details and structured JSON, search the web, and check account status from agents.

The langchain-mrscraper package exposes the seven MrScraper services as LangChain BaseTool instances, so AI agents can retrieve pages, extract brand details and structured JSON, search the web, and check account status. It wraps the Python SDK (mrscraper-sdk), which is installed as a dependency. MrScraper is also listed in LangChain's web browsing tools.

Tools-First Integration

This integration provides tools that agents can explicitly call—not a document loader. For deterministic "URL → documents" ingestion into vector stores, a document loader is typically a better fit. MrScraper may offer that in a separate package later.

Requirements

  • Python 3.9 or higher
  • mrscraper-sdk>=0.13.0,<0.14.0 and langchain-core 0.3 or later (installed as dependencies)

Package Information

This page documents version 0.8.0. Since 0.6.0, the page tools no longer accept super, proxy_country, proxy, wait_until, return_cookie, or save_result, accept max_age and custom screenshot viewports, and always save page results to your dashboard. See Migrating from 0.6.x. See langchain-mrscraper on PyPI for the latest release, version history, and installation details.

Installation

python -m pip install --upgrade langchain-mrscraper

This installs both the LangChain integration and the matching MrScraper Python SDK.

Authentication

Get an API key from the MrScraper app and set it as an environment variable:

export MRSCRAPER_API_KEY="YOUR_TOKEN"

Authentication Options

The tools resolve the key in this order:

  1. The token parameter, such as MrScraperToolkit(token="...")
  2. The mrscraper_api_key parameter, such as load_mrscraper_tools(mrscraper_api_key="...")
  3. The MRSCRAPER_API_KEY environment variable
  4. The MRSCRAPER_API_TOKEN environment variable

You can also pass an existing mrscraper.MrScraper client with client=.... Authentication is configured outside tool inputs, so the model never sees the key.

For more information on generating API tokens, see the Generate Token guide.

Quick Start

Using MrScraperToolkit

Load all seven tools with the toolkit:

from langchain_mrscraper import MrScraperToolkit

# Using environment variable
tools = MrScraperToolkit().get_tools()

# Or with explicit token
tools = MrScraperToolkit(token="MRSCRAPER_API_TOKEN").get_tools()

Using Convenience Loader

Alternatively, use the convenience function. It accepts the same configuration as the toolkit:

from langchain_mrscraper import load_mrscraper_tools

tools = load_mrscraper_tools()

Using with AI Agents

from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI
from langchain_mrscraper import MrScraperToolkit

# Load MrScraper tools
tools = MrScraperToolkit(token="MRSCRAPER_API_TOKEN").get_tools()

# Create agent with OpenAI
agent = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), tools)

# Use the agent
response = agent.invoke({
    "messages": [{"role": "user", "content": "Search the web for MrScraper and summarize the top result."}]
})

Prerequisites

This example requires langgraph and langchain-openai packages:

pip install langgraph langchain-openai

Invoking a tool directly

import json
from langchain_mrscraper import MrScraperScrapeHTML

result = json.loads(MrScraperScrapeHTML().invoke({
    "url": "https://example.com",
    "browser_rendering": True,
    "warm_start": True,
    "wait_for_selector": "body",
    "timeout": 120,
    "max_retries": 0,
}))
print(result["data"])

Examples use example.com as the sample target. Replace it for your use case. Scraping and search calls use tokens from your plan.

Available Tools

ClassTool nameSDK methodDescription
MrScraperStatusmrscraper_statusstatusReturn the raw account status API response without summarizing, redacting body fields, or adding calculated fields.
MrScraperScrapeHTMLmrscraper_scrape_htmlscrape_htmlRetrieve the raw HTML of a page. Browser rendering is optional.
MrScraperScrapeMarkdownmrscraper_scrape_markdownscrape_markdownRetrieve a page as clean Markdown. Browser rendering is optional.
MrScraperGetScreenshotmrscraper_get_screenshotget_screenshotCapture a base64 PNG screenshot of the full page, the first viewport, or a custom viewport. Browser rendering is always enabled.
MrScraperScrapeBrandmrscraper_scrape_brandscrape_brandExtract a website's colors, typography, logos, and social links as JSON.
MrScraperScrapeJSONmrscraper_scrape_jsonscrape_jsonExtract structured JSON from a page using a natural-language prompt. Append Json Schema: and a JSON schema to shape the output.
MrScraperWebSearchmrscraper_web_searchweb_searchSearch the web and return ranked results with titles, URLs, descriptions, and sources.

Tool Outputs

Every tool returns a JSON string containing the SDK's status_code, data, and headers. Parse it with json.loads. Binary bodies are represented as { "encoding": "base64", "base64": "...", "size_bytes": 123 }. Raw API nesting stays inside data; see the Python SDK methods for each response shape.

Tool Inputs

Tool inputs use snake_case and match the Python SDK arguments. A tool rejects fields it does not define, including any field passed to mrscraper_status.

Page controls

The HTML, Markdown, screenshot, and JSON tools accept these inputs.

ParameterTypeDefaultDescription
urlstrRequiredAbsolute HTTP or HTTPS URL of the page to process.
timeoutint300Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds.
wait_for_selectorstrOmittedCSS selector or text to wait for on the page before returning the result, up to 500 characters.
geo_codestrOmittedTwo-letter country code to load the page from, sent in lowercase. Omit it to load the page from the United States.
max_ageint0Return a cached result of the same request when it is newer than the selected age, in milliseconds, up to 604800000 (7 days). A cached result costs the same tokens as the original scrape. 0 always scrapes fresh.
max_retriesintOmittedMaximum number of retries, as a nonnegative integer. Omit this parameter for no limit.

Loading controls

The HTML, Markdown, and JSON tools also accept these inputs. mrscraper_get_screenshot does not.

ParameterTypeDefaultDescription
browser_renderingboolOmittedWhether to load the page in a browser: true always does and false never does. Omit it to load the page without a browser first and switch to a browser automatically if the request is blocked.
warm_startboolFalseWhether to open the site's home page first to warm the session before loading the target URL.
block_resourcesboolFalseWhether to block images, fonts, and stylesheets while loading the page.

Tool-specific inputs

ToolInputs
mrscraper_statusNone. The HTTP deadline is fixed at 600 seconds.
mrscraper_scrape_htmlPage and loading controls, screenshot (False, "full", "top", or a WIDTHxHEIGHT[-ZOOM] viewport such as "1280x800"; default False). Setting a screenshot also sends browserRendering=true and returns JSON with html and screenshot.
mrscraper_scrape_markdownPage and loading controls
mrscraper_get_screenshotPage controls, screenshot ("full", "top", or a WIDTHxHEIGHT[-ZOOM] viewport from 100 to 3840 pixels with an optional zoom from 25 to 300 percent; default "full")
mrscraper_scrape_brandurl only. The HTTP deadline is fixed at 120 seconds.
mrscraper_scrape_jsonPage and loading controls, prompt (default "Extract all data as complete as possible."), html (True), screenshot (False)
mrscraper_web_searchquery (required, 1 to 1000 characters), country (omitted, so the API searches from the United States), num_results (10 to 100, default 10). The HTTP deadline is fixed at 120 seconds.

Values always sent

Each tool adds its fixed request fields automatically; they are not inputs. The HTML, Markdown, screenshot, and JSON tools always send saveResult=true, so page results are saved to your dashboard, and tokenCap is never sent. mrscraper_scrape_html sends html=true and markdown=false; mrscraper_scrape_markdown sends markdown=true, html=false, and screenshot=false; mrscraper_get_screenshot sends browserRendering=true, html=false, and markdown=false, and the API still returns the page HTML; mrscraper_scrape_brand sends action=brand-scraping and bundle=none; mrscraper_scrape_json sends agent=general; and mrscraper_web_search sends action=websearch.

Examples

Scrape Markdown

import json
from langchain_mrscraper import MrScraperScrapeMarkdown

result = json.loads(MrScraperScrapeMarkdown().invoke({
    "url": "https://example.com",
    "warm_start": True,
    "max_age": 86400000,
}))
print(result["data"])

Get a screenshot

import json
from langchain_mrscraper import MrScraperGetScreenshot

result = json.loads(MrScraperGetScreenshot().invoke({
    "url": "https://example.com",
    "screenshot": "1280x800",
    "timeout": 120,
}))
print(result["data"]["screenshot"][:40])

Extract structured JSON

import json
from langchain_mrscraper import MrScraperScrapeJSON

result = json.loads(MrScraperScrapeJSON().invoke({
    "url": "https://example.com",
    "prompt": 'Extract the first 2 items with title and price. Json Schema: {"type":"array","items":{"type":"object","properties":{"title":{"type":"string"},"price":{"type":"string"}},"required":["title","price"]}}',
    "browser_rendering": True,
}))
print(result["data"]["data"])

Scrape brand

import json
from langchain_mrscraper import MrScraperScrapeBrand

result = json.loads(MrScraperScrapeBrand().invoke({"url": "https://example.com"}))
print(result["data"]["data"]["brand"])
import json
from langchain_mrscraper import MrScraperWebSearch

result = json.loads(MrScraperWebSearch().invoke({
    "query": "site:example.com documentation",
    "country": "id",
    "num_results": 20,
}))
for item in result["data"]["data"]:
    print(item["rank"], item["title"], item["url"])

Status

import json
from langchain_mrscraper import MrScraperStatus

result = json.loads(MrScraperStatus().invoke({}))
account = result["data"]["data"]
print(account["tokenUsage"], account["tokenLimit"])

Tool Loading Options

You can obtain tools in several ways:

1. Toolkit (Recommended)

from langchain_mrscraper import MrScraperToolkit

tools = MrScraperToolkit(token="MRSCRAPER_API_TOKEN").get_tools()

2. Convenience Loader

from langchain_mrscraper import load_mrscraper_tools

tools = load_mrscraper_tools(token="MRSCRAPER_API_TOKEN")

3. Selective Tool Loading

tool_names filters by the exact tool names. An empty list returns no tools.

from langchain_mrscraper import MrScraperToolkit

tools = MrScraperToolkit(
    token="MRSCRAPER_API_TOKEN",
    tool_names=["mrscraper_scrape_markdown", "mrscraper_web_search"],
).get_tools()

4. Per-Tool Constructors

from langchain_mrscraper import MrScraperScrapeHTML

scrape_html = MrScraperScrapeHTML(token="MRSCRAPER_API_TOKEN")

5. Shared SDK Client

MrScraperToolkit and load_mrscraper_tools share one SDK client across their tools. Pass your own client to reuse an HTTP connection pool; you manage the HTTP client's lifetime.

import httpx
from mrscraper import MrScraper
from langchain_mrscraper import MrScraperToolkit

http_client = httpx.AsyncClient()
client = MrScraper(token="MRSCRAPER_API_TOKEN", http_client=http_client)
tools = MrScraperToolkit(client=client).get_tools()

Async Usage

Every tool supports both .invoke(...) and await .ainvoke(...):

import asyncio
import json
from langchain_mrscraper import MrScraperToolkit

async def main():
    tools = MrScraperToolkit(tool_names=["mrscraper_scrape_markdown"]).get_tools()
    result = json.loads(await tools[0].ainvoke({"url": "https://example.com"}))
    print(result["data"])

asyncio.run(main())

Synchronous .invoke(...) calls also work inside notebooks that already have a running event loop.

Best Practices

Token Management

Store your API token securely:

import os

# Load from .env file
from dotenv import load_dotenv
load_dotenv()

token = os.getenv("MRSCRAPER_API_KEY")

Error Handling

Invalid tool inputs raise a Pydantic ValidationError before any request is sent. Authentication, HTTP, and network failures propagate as the Python SDK's AuthenticationError, APIError, and NetworkError; APIError.status_code contains the HTTP status when available. See Python SDK error handling.

from mrscraper import APIError, AuthenticationError, NetworkError
from langchain_mrscraper import MrScraperScrapeHTML

tool = MrScraperScrapeHTML(token="MRSCRAPER_API_TOKEN")
try:
    output = tool.invoke({"url": "https://example.com"})
except AuthenticationError as error:
    print("Check authentication:", error)
except APIError as error:
    print(error.status_code, error)
except NetworkError as error:
    print("Request failed:", error)

Tool Selection

Only load the tools your agent needs:

from langchain_mrscraper import MrScraperToolkit

# Good: Only load needed tools
tools = MrScraperToolkit(tool_names=["mrscraper_web_search"]).get_tools()

# Loads all seven tools
tools = MrScraperToolkit().get_tools()

Migrating from 0.6.x

Version 0.8.0 requires mrscraper-sdk>=0.13.0,<0.14.0. The seven tools and their names are unchanged; their inputs follow the Python SDK 0.13.0 arguments.

0.6.x input0.8.0
super, proxy_country, proxy, wait_until, return_cookieRemoved
save_resultRemoved; page results are always saved to your dashboard
mrscraper_scrape_markdown with "html": Truemrscraper_scrape_markdown for Markdown, or mrscraper_scrape_html for HTML
mrscraper_get_screenshot with html, markdown, block_resources, or browser_renderingmrscraper_get_screenshot with screenshot only; the API still returns the page HTML
"screenshot": "full" or "top"Also accepts a WIDTHxHEIGHT[-ZOOM] viewport, such as "1280x800"
  • max_age is new on every page tool. mrscraper_scrape_html accepts screenshot, and mrscraper_scrape_json accepts warm_start, block_resources, and wait_for_selector.
  • browser_rendering is omitted unless set, so the API switches to a browser only when a request is blocked.
  • geo_code and the mrscraper_web_search country input are omitted unless set, so the API uses the United States. The mrscraper_scrape_json html input now defaults to True.
  • Page timeouts accept up to 330 seconds.

From 0.5.x

Version 0.6.0 replaced MrScraperScraperAPI with MrScraperScrapeHTML, MrScraperScrapeMarkdown, and MrScraperGetScreenshot, replaced MrScraperAccount (mrscraper_account) with MrScraperStatus (mrscraper_status), and added MrScraperScrapeBrand and MrScraperScrapeJSON. mrscraper_status returns the raw API body, and status and search tools no longer accept a timeout input. Update tool_names filters to the new tool names.

From 0.3.x

The format-specific 0.3.x tools (MrScraperHTML, MrScraperMarkdown, MrScraperScreenshot, MrScraperJSON, MrScraperBrand) have counterparts in the 0.8.0 tools above; check their inputs against Tool Inputs. MrScraperMultiplePage, MrScraperSitemap, MrScraperGetBrand, and the MrScraperFetchHTML alias remain removed, as do the scraper and result tools from earlier versions. Call the REST API directly for scrapers and results.

On this page