SDKs

Python SDK

Install and use mrscraper-sdk, the typed async Python client for the MrScraper API, to fetch page content with the Scraper API and get Google search results with asyncio.

The mrscraper-sdk is a typed Python client for the MrScraper API. It exposes three methods: scraper_api to fetch page content (HTML, Markdown, or screenshots), web_search to get Google search results, and account to check your subscription and token usage. All client methods are async and must be used with asyncio or another async runtime.

Requirements

  • Python 3.9 or later
  • Basic familiarity with async/await syntax in Python

Package Information

This page documents version 0.6.0. See the mrscraper-sdk on PyPI for the latest release, version history, and metadata.

Installation

Install the SDK from PyPI using pip:

pip install --upgrade mrscraper-sdk

Import the client in your Python code:

from mrscraper import MrScraper

Authentication

The client reads your API token from the MRSCRAPER_API_TOKEN environment variable automatically. You can get your API token from the MrScraper dashboard.

export MRSCRAPER_API_TOKEN="MRSCRAPER_API_TOKEN"
from mrscraper import MrScraper

client = MrScraper()  # uses MRSCRAPER_API_TOKEN

You can also pass the token explicitly:

client = MrScraper(token="MRSCRAPER_API_TOKEN")

Custom HTTP client

Pass http_client= with your own httpx.AsyncClient to reuse connections across requests. Otherwise, the SDK creates a new client for each request.

import httpx
from mrscraper import MrScraper

async with httpx.AsyncClient() as http:
    client = MrScraper(http_client=http)
    result = await client.scraper_api("https://example.com")

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

Quick Start

import asyncio
from mrscraper import MrScraper

async def main():
    client = MrScraper()

    # 1. Fetch page content
    page = await client.scraper_api("https://example.com")
    print(page["data"])

    # 2. Search Google
    search = await client.web_search("python web scraping", raw=False)
    print(search["data"])

    # 3. Check remaining tokens
    account = await client.account()
    print(account["data"]["token_remaining"])

asyncio.run(main())

Response Format

All methods return a dictionary with the same structure:

KeyTypeDescription
status_codeintegerHTTP status code of the API response
dataanyParsed JSON when the API returns JSON, otherwise the response text
headersdictResponse headers

Note

Depending on the options you request, data may contain HTML, Markdown, a screenshot, or a combination. Inspect the returned value before assuming it is an HTML string.

Core Methods

Scraper API

Use scraper_api to fetch a page through the MrScraper Scraper API. The service handles JavaScript rendering, bot detection, and optional geolocation proxying.

import asyncio
from mrscraper import MrScraper

async def main():
    client = MrScraper()

    result = await client.scraper_api(
        "https://example.com/product",
        html=True,
        markdown=True,
        screenshot=True,
        geo_code="US",
        timeout=120,
    )
    print(result["data"])

asyncio.run(main())

Parameters:

ParameterTypeRequiredDefaultDescription
urlstringYes-Target page URL
htmlbooleanNoTrueReturn HTML content
markdownbooleanNoFalseReturn Markdown content
timeoutintegerNo120Page timeout in seconds (1-300)
geo_codestringNo"US"Two-letter country code for geolocation (e.g., "US", "GB", "SG")
proxy_countrystringNoNoneOptional proxy country
browser_renderingbooleanNoNoneTrue forces browser rendering, False disables it, None tries without a browser first and falls back automatically
screenshotbooleanNoFalseCapture a screenshot. Also forces browser rendering
superbooleanNoFalseEnable real device routing
use_proxybooleanNoTrueAllow the service to use a proxy
proxystringNoNoneCustom proxy in username:password@host:port format
home_pagebooleanNoFalseVisit the site's root page before the target URL
wait_for_selectorstringNoNoneCSS selector to wait for before returning content
block_resourcesbooleanNoFalseBlock images, CSS, and fonts to speed up the request
bypass_proxybooleanNoFalseEnable the API's proxy bypass behavior
cookie_jarstringNoNoneCookie configuration, e.g. "domain=example.com&country=us&max_used=100&max_age=50m"
headersdict | stringNoNoneHeaders forwarded to the target site, as a dictionary or JSON string
max_retriesintegerNo3Maximum number of retries
token_capintegerNoNoneOptional token budget for retries
streambooleanNoNoneRequest a streamed response. The SDK buffers it into the normal return value
discard_token_secretstringNo""Value sent in the x-discard-token-secret request header

Tip

Setting screenshot=True always enables browser rendering, even if you pass browser_rendering=False.

For more examples of what you can fetch, see Scrape HTML, Scrape Markdown, and Get Screenshot.

Use web_search to get Google search results. The first argument accepts either query text or a full Google search URL.

import asyncio
from mrscraper import MrScraper

async def main():
    client = MrScraper()

    result = await client.web_search(
        "python web scraping",
        raw=False,
        format="json",
        region="us",
        language="en",
        page=1,
    )
    print(result["data"])

asyncio.run(main())

You can also pass a Google search URL. The SDK extracts the q, gl, hl, and start parameters, and any options you pass explicitly override the values from the URL:

result = await client.web_search(
    "https://www.google.com/search?q=iphone+17&gl=us&hl=en",
)

Parameters:

ParameterTypeRequiredDefaultDescription
urlstringYes-Search query or Google search URL
rawbooleanNoTrueReturn HTML. When True, format is ignored
formatstringNo"json""json" or "html". Only used when raw=False
regionstringNoNoneCountry code (e.g., "us")
languagestringNoNoneLanguage code (e.g., "en")
pageintegerNoNoneResult page, starting at 1
render_jsbooleanNoFalseRender JavaScript-dependent result features
timeoutfloatNo600.0Request timeout in seconds

Note

raw defaults to True, so results are returned as HTML unless you set raw=False. To get structured JSON, pass raw=False and format="json".

Account

Use account to check the identity, subscription, token quota, and rate limits of the account that owns the API token.

import asyncio
from mrscraper import MrScraper

async def main():
    client = MrScraper()

    result = await client.account(timeout=30)
    print(result["data"]["subscription_status"])
    print(result["data"]["token_remaining"])
    print(result["data"]["user"]["email"])

asyncio.run(main())

Parameters:

ParameterTypeRequiredDefaultDescription
timeoutfloatNo30.0Request timeout in seconds. Must be greater than 0

Account summary (result["data"]):

KeyTypeDescription
subscription_statusstring | NoneSubscription status, such as "active"
enterprisebooleanWhether the account is on an enterprise plan
token_usagenumberTokens used in the current period
token_limitnumberToken limit for the current period
token_remainingnumberRemaining tokens, never below 0
usage_percentnumberToken usage as a percentage of the limit
rate_limitnumberRequest rate limit
rate_ttlnumberRate-limit window
auto_renewbooleanWhether the subscription renews automatically
ends_atstring | NoneSubscription end date
userdictname, email, and verified

Note

API keys, billing identifiers, and sensitive response headers are excluded from the result.

Error Handling

The SDK raises typed exceptions, which you can import from mrscraper or mrscraper.exceptions.

Exception Types

ExceptionWhen It's Raised
MrScraperErrorBase class for all SDK errors
AuthenticationErrorMissing or invalid API token (HTTP 401)
APIErrorNon-success API response (exposes .status_code)
NetworkErrorNetwork timeouts or connection failures

Invalid arguments, such as a timeout outside 1-300 or a page below 1, raise ValueError before any request is sent.

Example Error Handling

from mrscraper import MrScraper, AuthenticationError, APIError, NetworkError

client = MrScraper()

try:
    result = await client.scraper_api("https://example.com")
except AuthenticationError:
    print("Authentication failed. Check your API token at https://app.mrscraper.com")
except APIError as e:
    print(f"API error {e.status_code}: {e}")
except NetworkError as e:
    print(f"Network problem: {e}")

Best Practices

  • Always wrap SDK calls in try-except blocks
  • Log errors with appropriate context for debugging
  • Implement retry logic for NetworkError exceptions
  • Verify your API token if you encounter AuthenticationError

Migrating from Earlier Versions

From 0.5.0

Version 0.6.0 adds the account method. No existing methods changed.

From 0.4.0

Version 0.5.0 renames two public methods. Arguments and response formats are unchanged.

0.4.00.5.0
client.fetch_content(...)client.scraper_api(...)
client.google_serp(...)client.web_search(...)

The previous method names have been removed.

From 0.3.x and Earlier

fetch_html, fetch_google_serp, and the AI scraper, manual scraper, results, and account methods (create_scraper, rerun_scraper, bulk_rerun_ai_scraper, rerun_manual_scraper, bulk_rerun_manual_scraper, get_all_results, get_result_by_id, get_analytic_statuses) are no longer part of the SDK. get_subscription_account is replaced by account.

  • Replace fetch_html with scraper_api and fetch_google_serp with web_search. Both return a dictionary with status_code, data, and headers.
  • 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 MethodMrScraper Equivalent
Scrape a URL with HTML or Markdown outputscraper_api with html=True and/or markdown=True
Scrape a URL with a screenshotscraper_api with screenshot=True
Searchweb_search

On this page