# Cms Hospital Compare Scraper (`b2b_lead_generation/cms-hospital-compare-scraper`) Actor

Extract official U.S. hospital profiles, star ratings, and facility data in bulk. Set your state and filter preferences to instantly export clean records into structured JSON, CSV, or Excel files.

- **URL**: https://apify.com/b2b_lead_generation/cms-hospital-compare-scraper.md
- **Developed by:** [B2B Lead Generation](https://apify.com/b2b_lead_generation) (community)
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.99 / 1,000 results

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## CMS Hospital Compare Scraper: US Hospitals & Ratings

<p align="center">
  <img src="https://imgur.com/m7wkKU9.png" alt="CMS Hospital Compare Scraper" style="max-width:100%; border-radius:14px; width:680px;" />
</p>

Export general information, quality metrics, and operational details for U.S. hospitals directly from official healthcare catalogs. Gather comprehensive facility records—including addresses, contact numbers, ownership models, emergency services availability, and overall star ratings—into structured files ready for export as JSON, CSV, or Excel.

Instead of manually browsing through individual hospital profiles, you can extract reliable, clean datasets for entire states or targeted facility types in bulk.

### Use Cases

- **Hospital quality assessment:** Pull current overall star ratings, physical addresses, and contact numbers across specific states.
- **Healthcare directory building:** Export lists of acute-care facilities along with ownership types and emergency service flags.
- **Market & safety comparison:** Compare mortality, patient safety, and readmission measure counts across medical facilities.
- **Automated updates:** Keep spreadsheets and internal data pipelines refreshed with scheduled exports.
- **Research sample collection:** Extract structured healthcare data for analytical projects without dealing with complex web pagination.

### Extracted Data Points

Each facility entry captures detailed operational and performance attributes:

- Medicare Facility ID and hospital name
- Complete street address, city, state, ZIP code, and county
- Primary telephone number
- Hospital type and ownership category
- Emergency services and birthing-friendly designation indicators
- Overall star rating and associated rating footnotes
- Mortality, safety, and readmission performance measure counts (compared against national averages)

### Input Parameters

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `mode` | String | `rows` | Extraction mode (exports one dataset row per facility). |
| `datasetId` | String | `xubh-q36u` | Dataset identifier for Hospital General Information. |
| `state` | String | empty | Optional two-letter state abbreviation (e.g., `AL`). |
| `conditions` | Array | `[]` | Extra property and value filters for targeted queries. |
| `maxItems` | Integer | `100` | Maximum number of hospital rows to save (up to 1,000). |
| `timeoutSecs` | Integer | `300` | Overall execution limit in seconds. |

#### Example Input

```json
{
  "mode": "rows",
  "datasetId": "xubh-q36u",
  "state": "AL",
  "conditions": [
    {
      "property": "hospital_type",
      "value": "Acute Care Hospitals"
    }
  ],
  "maxItems": 100,
  "timeoutSecs": 300
}

```

### Output Format

```json
{
  "facility_id": "010001",
  "facility_name": "SOUTHEAST HEALTH MEDICAL CENTER",
  "address": "1108 ROSS CLARK CIRCLE",
  "citytown": "DOTHAN",
  "state": "AL",
  "zip_code": "36301",
  "countyparish": "HOUSTON",
  "telephone_number": "(334) 793-8701",
  "hospital_type": "Acute Care Hospitals",
  "hospital_ownership": "Government - Hospital District or Authority",
  "emergency_services": "Yes",
  "meets_criteria_for_birthing_friendly_designation": "Y",
  "hospital_overall_rating": "4",
  "hospital_overall_rating_footnote": ""
}

```

### How It Works

1. Processes input options, building state filters and optional property criteria.
2. Formats requests efficiently to fetch records in structured batches.
3. Deduplicates entries based on unique facility identifiers.
4. Handles brief network hiccups using retry delays to maintain execution stability.
5. Exports clean hospital records ready for download in CSV, JSON, or Excel format.

### Frequently Asked Questions

**How many hospital records can I export in a single run?**

The default limit per run is set to 100 rows, but you can increase `maxItems` up to 1,000 rows.

**What happens if I specify an unknown filter property?**

If an invalid filter or dataset property is submitted, an error entry explaining the issue will be logged, allowing the execution to complete without crashing.

**Can I export datasets directly to CSV or Excel?**

Yes. Once completed, your dataset can be downloaded instantly in JSON, CSV, or Excel formats.

***

### Legal & Compliance

#### Trademark Notice

CMS Hospital Compare and related names, logos, and trademarks belong to their respective owners. Their mention in this documentation is strictly to identify data compatibility and utility, and does not imply affiliation, sponsorship, or endorsement.

#### Disclaimer

This tool is an independent utility and is not affiliated with, endorsed by, or officially connected to third-party healthcare data providers. Users are responsible for ensuring their usage complies with relevant terms of service and local guidelines.

#### Is web scraping legal?

This tool collects publicly available healthcare information without bypassing access controls. Collecting public data is standard practice, but proper compliance requires considering how the data is used:

- **Personal data:** Ensure dataset usage respects regional privacy regulations (such as GDPR or CCPA) when combining outputs with personal user records.
- **Copyright & Terms:** Respect the terms of use, usage limits, and licensing terms set by the data source.
- **Legal advice:** This summary is provided for general informational purposes and does not constitute formal legal counsel.

# Actor input Schema

## `mode` (type: `string`):

What to export. rows writes one dataset item per hospital from the CMS Provider Data query.

## `datasetId` (type: `string`):

CMS Provider Data dataset identifier. The verified hospital general information dataset is xubh-q36u.

## `state` (type: `string`):

Optional 2-letter US state code. Leave empty to include every state. Example: AL.

## `conditions` (type: `array`):

Optional property and value filters sent to the CMS datastore query. Each object needs property and value. Example: hospital_type equals Acute Care Hospitals.

## `maxItems` (type: `integer`):

Maximum hospital rows to save this run. Free cap, hard max 1000.

## `timeoutSecs` (type: `integer`):

Overall run limit in seconds. The actor stops requesting when this elapses.

## `requestTimeoutSecs` (type: `integer`):

Per-request timeout in seconds for each CMS query.

## `proxyConfiguration` (type: `object`):

Optional proxy for CMS requests. Off by default. The public catalog answers without a proxy. Turn one on only if your network needs it.

## Actor input object example

```json
{
  "mode": "rows",
  "datasetId": "xubh-q36u",
  "state": "AL",
  "conditions": [
    {
      "property": "hospital_type",
      "value": "Acute Care Hospitals"
    }
  ],
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `dataset` (type: `string`):

Default dataset URL for the hospital rows saved in this run.

## `datasetItems` (type: `string`):

JSON items endpoint for the default dataset.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "mode": "rows",
    "datasetId": "xubh-q36u",
    "conditions": [],
    "maxItems": 100,
    "timeoutSecs": 300,
    "requestTimeoutSecs": 30,
    "proxyConfiguration": {
        "useApifyProxy": false
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("b2b_lead_generation/cms-hospital-compare-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "mode": "rows",
    "datasetId": "xubh-q36u",
    "conditions": [],
    "maxItems": 100,
    "timeoutSecs": 300,
    "requestTimeoutSecs": 30,
    "proxyConfiguration": { "useApifyProxy": False },
}

# Run the Actor and wait for it to finish
run = client.actor("b2b_lead_generation/cms-hospital-compare-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "mode": "rows",
  "datasetId": "xubh-q36u",
  "conditions": [],
  "maxItems": 100,
  "timeoutSecs": 300,
  "requestTimeoutSecs": 30,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}' |
apify call b2b_lead_generation/cms-hospital-compare-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,b2b_lead_generation/cms-hospital-compare-scraper"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/12PHjgLgV1qiQm8JJ/builds/Ui820ar6BxTV7WL6e/openapi.json
