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 clean Markdown. Browser rendering is optional. |
get_screenshot | Capture a base64 PNG screenshot of the full page, the first viewport, or a custom 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.13.0. Since 0.11.0, the page methods 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.11.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 | Maximum seconds to wait for the scrape, from 1 to 330. The HTTP request allows 30 additional seconds. |
wait_for_selector | str | None | CSS selector or text to wait for on the page before returning the result, up to 500 characters. |
geo_code | str | None | 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 | None | Maximum number of retries, as a nonnegative integer. Omit this parameter for no limit. |
Loading controls
scrape_html, scrape_markdown, and scrape_json also accept these arguments. get_screenshot does not.
| Parameter | Type | Default | Description |
|---|---|---|---|
browser_rendering | bool | None | 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. |
Values always sent
Each method adds its fixed request fields automatically; they are not arguments. scrape_html, scrape_markdown, get_screenshot, and scrape_json also always send saveResult=true, so page results are saved to your dashboard. tokenCap is never sent.
| Method | Fixed fields |
|---|---|
scrape_html | html=true and markdown=false, plus browserRendering=true when a screenshot is set |
scrape_markdown | markdown=true, html=false, and screenshot=false |
get_screenshot | browserRendering=true, html=false, and markdown=false |
scrape_brand | action=brand-scraping and bundle=none |
scrape_json | agent=general |
web_search | action=websearch |
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 |
|---|---|---|---|
screenshot | False or str | False | Screenshot to capture with the HTML: false for none, full for the entire page, top for the first viewport, or a WIDTHxHEIGHT viewport from 100 to 3840 pixels with an optional -ZOOM percent from 25 to 300, such as 1280x800 or 1920x1080-75. Setting a screenshot also sends browserRendering=true. |
result = await client.scrape_html(
"https://example.com",
browser_rendering=True,
wait_for_selector="body",
)
print(result["data"])The response body is HTML text. With a screenshot, data is a dictionary containing html and a base64 screenshot:
{
"status_code": 200,
"data": {
"html": "<html>...</html>",
"screenshot": "BASE64_IMAGE_DATA"
},
"headers": {
"content-type": "application/json; charset=utf-8"
}
}scrape_markdown
Retrieve a page as clean Markdown. Browser rendering is optional.
Accepts page controls and loading controls.
result = await client.scrape_markdown("https://example.com", warm_start=True, max_age=86400000)
print(result["data"])The response body is Markdown text.
get_screenshot
Capture a base64 PNG screenshot of the full page, the first viewport, or a custom viewport. Browser rendering is always enabled.
Accepts page controls and:
| Parameter | Type | Default | Description |
|---|---|---|---|
screenshot | str | "full" | Screenshot area to capture: full for the entire scroll height, top for the first viewport, or a WIDTHxHEIGHT viewport from 100 to 3840 pixels with an optional -ZOOM percent from 25 to 300, such as 1280x800 or 1920x1080-75. |
import base64
result = await client.get_screenshot("https://example.com", screenshot="1280x800", timeout=120)
with open("page.png", "wb") as f:
f.write(base64.b64decode(result["data"]["screenshot"]))The response body is JSON containing a base64 PNG screenshot and the page HTML, which the API includes even though html=false is sent.
{
"status_code": 200,
"data": {
"html": "<html>...</html>",
"screenshot": "BASE64_PNG_DATA"
},
"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, loading 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. |
html | bool | True | Whether to include the page HTML in the response. |
screenshot | bool | False | Whether to include a base64 screenshot in the response. |
The request uses GET. If the encoded URL exceeds 8,000 characters, it switches to POST with url, prompt, and agent in the body; page controls remain in the query.
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 contains the page HTML unless disabled; markdown and screenshot can be empty strings.
{
"status_code": 200,
"data": {
"success": true,
"data": [{ "title": "Example item", "price": "10.00" }],
"thread_id": "THREAD_ID",
"token_usage": 1,
"html": "<html>...</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 | None | Two-letter country code to search from, sent in lowercase. Omit it to search from the United States. |
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 330.
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.11.x
Versions 0.12.0 and 0.13.0 keep the seven methods and change their arguments.
| 0.11.x | 0.13.0 |
|---|---|
super, proxy_country, proxy, wait_until, return_cookie | Removed |
save_result | Removed; page results are always saved to your dashboard |
client.scrape_markdown(url, html=True) | client.scrape_markdown(url) for Markdown, or client.scrape_html(url) for HTML |
client.get_screenshot(url, html=..., markdown=..., block_resources=..., browser_rendering=...) | client.get_screenshot(url, screenshot=...); 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 method.scrape_htmlacceptsscreenshot, andscrape_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.get_screenshotno longer accepts it and always sendsbrowserRendering=true.geo_codeand theweb_searchcountryargument are omitted unless set, so the API uses the United States. Thescrape_jsonhtmlargument now defaults toTrue.- Page timeouts accept up to 330 seconds.
Earlier versions
- 0.9.x to 0.11.0:
scraper_apiwas replaced byscrape_html,scrape_markdown, andget_screenshot, andaccountbystatus, which returns the raw API body.scrape_brandandscrape_jsonwere added. - 0.7.x to 0.9.0: the format-specific 0.7.x methods were merged into
scraper_api. Upgrade directly to the 0.13.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.