Python SDK
Install and use mrscraper-sdk, the async Python client for the MrScraper API, to retrieve pages as HTML, Markdown, or screenshots, extract brand details and structured JSON, search the web, and check account status.
The mrscraper-sdk is an async Python client for the seven MrScraper services. Its methods share their descriptions, parameter meanings, and defaults with the MCP server, the CLI, the Node.js SDK, and the other integrations. All client methods are async and must be awaited with asyncio or another async runtime.
| Method | Description |
|---|---|
status | Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields. |
scrape_html | Retrieve the raw HTML of a page. Browser rendering is optional. |
scrape_markdown | Retrieve a page as Markdown. Including HTML also enables browser rendering and returns both outputs as JSON. |
get_screenshot | Capture a base64 screenshot of the full page or top viewport. Browser rendering is always enabled. |
scrape_brand | Extract a website's colors, typography, logos, and social links as 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. |
web_search | Search the web and return ranked results with titles, URLs, descriptions, and sources. |
Requirements
- Python 3.9 or later
- Basic familiarity with async/await syntax in Python
Package Information
This page documents version 0.11.0. Version 0.11.0 replaces scraper_api with scrape_html, scrape_markdown, and get_screenshot, replaces account with status, and adds scrape_brand and scrape_json. See Migrating from 0.9.x. See mrscraper-sdk on PyPI for the latest release, version history, and metadata.
Installation
python -m pip install --upgrade mrscraper-sdkImport the client in your Python code:
from mrscraper import MrScraperAuthentication
Get an API key from the MrScraper app and set it as an environment variable:
export MRSCRAPER_API_TOKEN="YOUR_TOKEN"Use MrScraper() to read the environment, or MrScraper(token="YOUR_TOKEN") to pass the key explicitly. The client uses a nonempty token first, then MRSCRAPER_API_TOKEN, then MRSCRAPER_API_KEY. Authentication belongs to the client and is not a method parameter.
For more information on generating API tokens, see the Generate Token guide.
Custom HTTP client
Pass http_client=httpx.AsyncClient(...) to reuse a connection pool. You manage the lifetime of a client you supply; otherwise the SDK creates and closes its own. Each service's HTTP deadline still applies with a shared client.
import asyncio
import httpx
from mrscraper import MrScraper
async def main():
async with httpx.AsyncClient() as http_client:
client = MrScraper(http_client=http_client)
print((await client.status())["data"])
print((await client.scrape_markdown("https://example.com"))["data"])
asyncio.run(main())Quick Start
import asyncio
from mrscraper import MrScraper
async def main():
client = MrScraper()
result = await client.scrape_html(
"https://example.com",
browser_rendering=True,
warm_start=True,
wait_for_selector="body",
timeout=120,
max_retries=0,
)
print(result["data"])
asyncio.run(main())Examples use example.com as the sample target. Replace it for your use case. Scraping and search calls use tokens from your plan. Inside a notebook with a running event loop, use await main() instead of asyncio.run(main()).
Response Format
Every method returns a dictionary:
| Key | Type | Description |
|---|---|---|
status_code | int | HTTP status code of the API response |
data | Any | The API response body. JSON becomes Python values, text stays a str, and binary bodies become bytes |
headers | dict | Response headers. Sensitive headers are removed for status |
Field names inside data are returned as the API sends them and are not converted to snake_case.
{
"status_code": 200,
"data": "<html><body>Example page content...</body></html>",
"headers": {
"content-type": "text/html; charset=utf-8"
}
}Response examples below show selected keys with placeholder values. Actual responses may contain additional fields.
Shared Parameters
The first argument is the target URL (or the search query for web_search). Other parameters are keyword arguments in snake_case. Optional controls set to None are omitted from the request; explicit False and 0 are sent as given. You can unpack a dictionary of options with **payload.
Page controls
scrape_html, scrape_markdown, get_screenshot, and scrape_json accept these arguments.
| Parameter | Type | Default | Description |
|---|---|---|---|
url | str | Required | Absolute HTTP or HTTPS URL of the page to process. |
timeout | int | 300 | Page load timeout in seconds, from 1 to 300. The HTTP request allows 30 additional seconds. |
geo_code | str | "us" | Two-letter country code to load the page from, sent in lowercase. |
proxy_country | str | "us" | Two-letter country code of the proxy server, sent in lowercase. |
super | bool | False | Whether to route the request through real devices. |
wait_until | str: domcontentloaded, load, networkidle0, networkidle2 | "domcontentloaded" | Navigation completion event to wait for: domcontentloaded, load, networkidle0, or networkidle2. |
proxy | str | None | Custom proxy URL used to load the page. |
max_retries | int | None | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
save_result | bool | False | Whether to save the result to the dashboard Result tab. |
Loading controls
scrape_html, scrape_markdown, and get_screenshot also accept these arguments. scrape_json does not.
| Parameter | Type | Default | Description |
|---|---|---|---|
block_resources | bool | False | Whether to block images, fonts, and stylesheets while loading the page. |
wait_for_selector | str | None | Wait for the page to contain the specified CSS selector before returning the result. |
return_cookie | bool | False | Whether to include browser session cookies in the response. |
Browser rendering is optional for HTML, Markdown, and JSON; screenshots always enable it. Markdown with HTML also enables browser rendering.
Methods
status
Return the raw account status API response without summarizing, redacting body fields, or adding calculated fields. It takes no service parameters, and its HTTP deadline is fixed at 600 seconds.
import asyncio
from mrscraper import MrScraper
async def main():
result = await MrScraper().status()
account = result["data"]["data"]
print(account["tokenUsage"], account["tokenLimit"])
asyncio.run(main())The API body contains message and data. Account details remain nested in data, including subscriptionItem and scraperAllowance, so the response exposes them at result["data"]["data"].
{
"status_code": 200,
"data": {
"message": "Example response",
"data": {
"id": "ACCOUNT_ID",
"tokenLimit": 100000,
"tokenUsage": 2500,
"stripeStatus": "active",
"user": {
"name": "Example user",
"email": "user@example.com",
"isVerified": true
},
"subscriptionItem": {
"name": "Example plan",
"tokenLimit": 100000
},
"scraperAllowance": {
"remaining": 97500,
"plans": [{ "remaining": 97500 }]
}
}
},
"headers": {
"content-type": "application/json; charset=utf-8"
}
}scrape_html
Retrieve the raw HTML of a page. Browser rendering is optional.
Accepts page controls, loading controls, and:
| Parameter | Type | Default | Description |
|---|---|---|---|
browser_rendering | bool | False | Whether to render the page in a browser before returning the result. |
warm_start | bool | False | Whether to enable warm start for more reliable scraping, at the cost of additional latency. |
result = await client.scrape_html(
"https://example.com",
browser_rendering=True,
wait_for_selector="body",
)
print(result["data"])The default response body is HTML text. Additional controls can cause the API to return JSON; the returned structure is preserved.
scrape_markdown
Retrieve a page as Markdown. Including HTML also enables browser rendering and returns both outputs as JSON.
Accepts page controls, loading controls, and:
| Parameter | Type | Default | Description |
|---|---|---|---|
browser_rendering | bool | False | Whether to render the page in a browser before returning the result. |
warm_start | bool | False | Whether to enable warm start for more reliable scraping, at the cost of additional latency. |
html | bool | False | Whether to include the page HTML in the response. |
result = await client.scrape_markdown("https://example.com", html=True, warm_start=True)
print(result["data"]["markdown"])The default response body is Markdown text. With html=True, data is a dictionary containing both outputs:
{
"status_code": 200,
"data": {
"html": "<html>...</html>",
"markdown": "# Example page\n\n..."
},
"headers": {
"content-type": "application/json"
}
}get_screenshot
Capture a base64 screenshot of the full page or top viewport. Browser rendering is always enabled.
Accepts page controls, loading controls, and:
| Parameter | Type | Default | Description |
|---|---|---|---|
screenshot | str: full, top | "full" | Screenshot area to capture: full for the entire page or top for the top viewport. |
html | bool | True | Whether to include the page HTML in the response. |
markdown | bool | False | Whether to include the page Markdown in the response. |
import base64
result = await client.get_screenshot("https://example.com", screenshot="top", html=False)
with open("page.png", "wb") as f:
f.write(base64.b64decode(result["data"]["screenshot"]))The response body contains a base64 screenshot and the requested page outputs. The API can still include HTML when HTML output is disabled.
{
"status_code": 200,
"data": {
"html": "<html>...</html>",
"screenshot": "BASE64_PNG_DATA",
"markdown": "# Example page\n\n..."
},
"headers": {
"content-type": "application/json; charset=utf-8"
}
}scrape_brand
Extract a website's colors, typography, logos, and social links as JSON. It takes only the URL; page controls are not accepted. The HTTP deadline is fixed at 120 seconds.
result = await client.scrape_brand("https://example.com")
print(result["data"]["data"]["brand"])The API body contains message and a data object with job_id, status, url, final_url, brand, and error. Brand details are at result["data"]["data"]["brand"].
{
"status_code": 200,
"data": {
"data": {
"job_id": "JOB_ID",
"status": "succeeded",
"url": "https://example.com",
"final_url": "https://example.com",
"brand": {
"name": "Example brand",
"colors": { "background": "#ffffff", "text": "#222222" },
"typography": { "body": { "font_family": "Example font" } }
},
"error": null,
"bundle_url": null
},
"message": "Example response"
},
"headers": {
"content-type": "application/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.
Accepts page controls and:
| Parameter | Type | Default | Description |
|---|---|---|---|
prompt | str | "Extract all data as complete as possible." | Instructions describing the data to extract. Append Json Schema: and a JSON schema to shape the output. |
browser_rendering | bool | False | Whether to render the page in a browser before returning the result. |
html | bool | False | Whether to include the page HTML in the response. |
screenshot | bool | False | Whether to include a base64 screenshot in the response. |
result = await client.scrape_json(
"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"])Extraction results are in the API body's data field and follow the requested schema. Response metadata includes thread_id, token_usage, status, error, runtime, and cookies. html, markdown, and screenshot can be empty strings when not requested.
{
"status_code": 200,
"data": {
"success": true,
"data": [{ "title": "Example item", "price": "10.00" }],
"thread_id": "THREAD_ID",
"token_usage": 1,
"html": "",
"markdown": "",
"screenshot": "",
"status": "Results ready",
"error": "",
"runtime": 1.23,
"cookies": []
},
"headers": {
"content-type": "application/json"
}
}web_search
Search the web and return ranked results with titles, URLs, descriptions, and sources. The first argument is the search query. The HTTP deadline is fixed at 120 seconds.
| Parameter | Type | Default | Description |
|---|---|---|---|
query | str | Required | Search query text, trimmed before sending, containing 1 to 1000 characters. |
country | str | "us" | Two-letter country code to search from, sent in lowercase. |
num_results | int | 10 | Number of search results to request, as an integer from 10 to 100. Fewer results may be returned. |
result = await client.web_search("site:example.com documentation", country="id", num_results=20)
for item in result["data"]["data"]:
print(item["rank"], item["title"], item["url"])The API body contains success, message, a data array, and tokenUsage. Each result includes rank, title, url, description, and source.
{
"status_code": 200,
"data": {
"success": true,
"message": "Example response",
"data": [
{
"rank": 1,
"title": "Example result",
"url": "https://example.com",
"description": "Example result description.",
"source": "example.com"
}
],
"tokenUsage": 1
},
"headers": {
"content-type": "application/json; charset=utf-8"
}
}Error Handling
Invalid arguments raise ValueError or TypeError before any request is sent. Request failures raise these exceptions, all subclasses of MrScraperError:
| Exception | When It's Raised |
|---|---|
AuthenticationError | Missing or invalid API key |
APIError | Any other HTTP error status. status_code contains the HTTP status when available |
NetworkError | Connection or timeout failures |
import asyncio
from mrscraper import MrScraper, APIError, AuthenticationError, NetworkError
async def main():
try:
await MrScraper().scrape_html("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)
asyncio.run(main())Troubleshooting
- If authentication fails, check the token precedence described in Authentication.
- Use snake_case argument names, not the camelCase HTTP field names.
- Page timeouts are integers from 1 to 300.
status,scrape_brand, andweb_searchhave fixed deadlines and do not accept a timeout. - Inspect the raw API body before selecting nested fields.
Migrating from Earlier Versions
From 0.9.x
Version 0.11.0 replaces the three 0.9.x methods with seven service methods.
| 0.9.x | 0.11.0 |
|---|---|
client.scraper_api(url) | client.scrape_html(url) |
client.scraper_api(url, html=False, markdown=True) | client.scrape_markdown(url) |
client.scraper_api(url, html=True, markdown=True) | client.scrape_markdown(url, html=True) |
client.scraper_api(url, html=False, screenshot=True) | client.get_screenshot(url, html=False) |
client.scraper_api(url, home_page=True) | client.scrape_html(url, warm_start=True) |
client.account() | client.status() |
statusreturns the raw API body. The normalized 0.9.x summary fields such astoken_remainingandusage_percentare gone; readresult["data"]["data"]instead.statusandweb_searchno longer accept atimeoutargument.- Defaults changed: page
timeoutis now300,geo_codeandproxy_countrydefault to"us", and an omittedmax_retriesmeans no limit. use_proxy,bypass_proxy,cookie_jar,headers,token_cap,stream, anddiscard_token_secretare no longer accepted.scrape_brandandscrape_jsonare new.
Earlier versions
- 0.7.x to 0.9.0: the format-specific 0.7.x methods were merged into
scraper_api. Upgrade directly to the 0.11.0 methods above. - 0.6.0 to 0.7.x:
web_searchmoved toaction: "websearch"withcountryandnum_results. - 0.5.0 to 0.6.0: added
account. - 0.4.0 to 0.5.0:
fetch_contentwas renamedscraper_api. - 0.3.x and earlier:
fetch_htmland the AI scraper, manual scraper, results, and analytics methods were removed. For scrapers, results, and analytics, call the REST API directly.
Migration from Firecrawl
If you're migrating from the Firecrawl Python SDK, use this mapping to find equivalent MrScraper methods.
| Firecrawl Method | MrScraper Equivalent |
|---|---|
| Scrape a URL with HTML output | scrape_html |
| Scrape a URL with Markdown output | scrape_markdown |
| Scrape a URL with a screenshot | get_screenshot |
| Scrape a URL with JSON extraction | scrape_json |
| Scrape a URL with branding | scrape_brand |
| Search | web_search |
Scalekit
Connect MrScraper MCP through Scalekit AgentKit to give your AI agents per-user web fetching, web search, and account usage tools.
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.