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.0andlangchain-core0.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-mrscraperThis 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:
- The
tokenparameter, such asMrScraperToolkit(token="...") - The
mrscraper_api_keyparameter, such asload_mrscraper_tools(mrscraper_api_key="...") - The
MRSCRAPER_API_KEYenvironment variable - The
MRSCRAPER_API_TOKENenvironment 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-openaiInvoking 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
| Class | Tool name | SDK method | Description |
|---|---|---|---|
MrScraperStatus | mrscraper_status | status | Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields. |
MrScraperScrapeHTML | mrscraper_scrape_html | scrape_html | Retrieve the raw HTML of a page. Browser rendering is optional. |
MrScraperScrapeMarkdown | mrscraper_scrape_markdown | scrape_markdown | Retrieve a page as clean Markdown. Browser rendering is optional. |
MrScraperGetScreenshot | mrscraper_get_screenshot | get_screenshot | Capture a base64 PNG screenshot of the full page, the first viewport, or a custom viewport. Browser rendering is always enabled. |
MrScraperScrapeBrand | mrscraper_scrape_brand | scrape_brand | Extract a website's colors, typography, logos, and social links as JSON. |
MrScraperScrapeJSON | mrscraper_scrape_json | scrape_json | Extract structured JSON from a page using a natural-language prompt. Append Json Schema: and a JSON schema to shape the output. |
MrScraperWebSearch | mrscraper_web_search | web_search | Search 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
url | str | Required | Absolute HTTP or HTTPS URL of the page to process. |
timeout | int | 300 | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
wait_for_selector | str | Omitted | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
geo_code | str | Omitted | Two-letter country code to load the page from, sent in lowercase. Omit it to load the page from the United States. |
max_age | int | 0 | Return 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_retries | int | Omitted | Maximum 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.
| Parameter | Type | Default | Description |
|---|---|---|---|
browser_rendering | bool | Omitted | Whether 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_start | bool | False | Whether to open the site's home page first to warm the session before loading the target URL. |
block_resources | bool | False | Whether to block images, fonts, and stylesheets while loading the page. |
Tool-specific inputs
| Tool | Inputs |
|---|---|
mrscraper_status | None. The HTTP deadline is fixed at 600 seconds. |
mrscraper_scrape_html | Page 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_markdown | Page and loading controls |
mrscraper_get_screenshot | Page 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_brand | url only. The HTTP deadline is fixed at 120 seconds. |
mrscraper_scrape_json | Page and loading controls, prompt (default "Extract all data as complete as possible."), html (True), screenshot (False) |
mrscraper_web_search | query (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"])Web search
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 input | 0.8.0 |
|---|---|
super, proxy_country, proxy, wait_until, return_cookie | Removed |
save_result | Removed; page results are always saved to your dashboard |
mrscraper_scrape_markdown with "html": True | mrscraper_scrape_markdown for Markdown, or mrscraper_scrape_html for HTML |
mrscraper_get_screenshot with html, markdown, block_resources, or browser_rendering | mrscraper_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_ageis new on every page tool.mrscraper_scrape_htmlacceptsscreenshot, andmrscraper_scrape_jsonacceptswarm_start,block_resources, andwait_for_selector.browser_renderingis omitted unless set, so the API switches to a browser only when a request is blocked.geo_codeand themrscraper_web_searchcountryinput are omitted unless set, so the API uses the United States. Themrscraper_scrape_jsonhtmlinput now defaults toTrue.- 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.
Node.js SDK
Install the official @mrscraper/sdk package to retrieve pages as HTML, Markdown, or screenshots, extract brand details and structured JSON, search the web, and check account status from Node.js.
Vercel AI SDK
Give AI SDK agents MrScraper tools: retrieve public pages as Markdown, HTML, or screenshots, search the web, and check account usage with @mrscraper/ai-sdk.