> ## Documentation Index
> Fetch the complete documentation index at: https://docs.zenrows.com/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> The Zenrows HTTP API serves Fetch and Extract (extract=auto) at https://api.zenrows.com/v1/, Crawl at https://api.zenrows.com/v1/crawls, and Batch at https://async.api.zenrows.com/v1. Fetch, Extract, Crawl and Batch are described in OpenAPI 3.1 at https://www.zenrows.com/openapi.json and listed in the RFC 9727 API catalog at https://www.zenrows.com/.well-known/api-catalog. Every endpoint also has its own page under /api-reference with its schema. Use the spec for exact parameter names and types. Crawl's endpoints, parameters and errors are also at https://docs.zenrows.com/crawl/endpoints.md. To call Zenrows from an agent, connect the MCP server at https://mcp.zenrows.com/mcp. To search these docs from an agent, connect the docs MCP server at https://docs.zenrows.com/mcp. Agent skills for Zenrows are published at https://github.com/ZenRows/cli and install with `npx skills add ZenRows/cli`.

# Integrating the Zenrows Browser with Playwright

> Step-by-step guide to connect the Zenrows Browser with Playwright for Python and Node.js web scraping and browser automation.

Learn to extract data from any website using the Zenrows Browser (formerly, Scraping Browser) with Playwright. This guide walks you through creating your first browser-based scraping request that can handle complex JavaScript-heavy sites with full browser automation.

The Zenrows Browser provides cloud-based Chrome instances you can control using Playwright. Whether dealing with dynamic content, complex user interactions, or sophisticated anti-bot protection, you can get started in minutes with Playwright's powerful automation capabilities.

## 1. Set Up Your Project

### Set Up Your Development Environment

Before diving in, ensure you have the proper development environment and Playwright installed. The Zenrows Browser works seamlessly with both Python and Node.js versions of Playwright.

> [!NOTE]
>
> While previous versions may work, we recommend using the latest stable versions for optimal performance and security.

> [tab] Python
>
> Python 3+ installed (latest stable version recommended). Using an IDE like [PyCharm](https://www.jetbrains.com/pycharm/) or [Visual Studio Code](https://code.visualstudio.com/docs/languages/python) with the Python extension is recommended.
>
> ```bash theme={"theme":"css-variables"}
> # Install Python (if not already installed)
> # Visit https://www.python.org/downloads/ or use package managers:
>
> # macOS (using Homebrew)
> brew install python
>
> # Ubuntu/Debian
> sudo apt update && sudo apt install python3 python3-pip
>
> # Windows (using Chocolatey)
> choco install python
>
> # Install Playwright
> pip install playwright
> playwright install
> ```
>
> > [!TIP]
> >
> > If you need help setting up your environment, check out our detailed [Playwright web scraping guide](https://www.zenrows.com/blog/playwright-scraping)

> [tab] Node.js
>
> Node.js 18+ installed (latest LTS version recommended). Using an IDE like [Visual Studio Code](https://code.visualstudio.com/) or [IntelliJ IDEA](https://www.jetbrains.com/idea/) will enhance your coding experience.
>
> ```bash theme={"theme":"css-variables"}
> # Install Node.js (if not already installed)
> # Visit https://nodejs.org/ or use package managers:
>
> # macOS (using Homebrew)
> brew install node
>
> # Ubuntu/Debian (using NodeSource)
> curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
> sudo apt-get install -y nodejs
>
> # Windows (using Chocolatey)
> choco install nodejs
>
> # Install Playwright
> npm install playwright
> npx playwright install
> ```
>
> > [!TIP]
> >
> > If you need help setting up your environment, check out our detailed [Playwright web scraping guide](https://www.zenrows.com/blog/playwright-scraping)

### Get Your API Key and Connection URL

Sign up for a free Zenrows account and get your API key from the Zenrows Browser dashboard. You'll need this key to authenticate your WebSocket connection.

[Sign up free](https://app.zenrows.com/register?prod=scraping_browser)
[Open the Zenrows Browser](https://app.zenrows.com/browser)

## 2. Make Your First Request

Start with a simple request to understand how the Zenrows Browser works with Playwright. We'll use the [E-commerce Challenge](https://www.scrapingcourse.com/ecommerce/) page to demonstrate how to connect to the browser and extract the page title.

```python Python theme={"theme":"css-variables"}
# pip install playwright
import asyncio
from playwright.async_api import async_playwright

# scraping browser connection URL
connection_url = "wss://browser.zenrows.com?apikey=YOUR_ZENROWS_API_KEY"

async def scraper():
    async with async_playwright() as p:
        # connect to the scraping browser
        browser = await p.chromium.connect_over_cdp(connection_url)
        context = browser.contexts[0] if browser.contexts else await browser.new_context()
        page = await context.new_page()
        
        await page.goto('https://www.scrapingcourse.com/ecommerce/')
        print(await page.title())
        
        await browser.close()

if __name__ == "__main__":
    asyncio.run(scraper())
```

```javascript Node.js theme={"theme":"css-variables"}
// npm install playwright
const { chromium } = require('playwright');

// scraping browser connection URL
const connectionURL = 'wss://browser.zenrows.com?apikey=YOUR_ZENROWS_API_KEY';

const scraper = async () => {
    // connect to the scraping browser
    const browser = await chromium.connectOverCDP(connectionURL);
    const page = await browser.newPage();
    
    await page.goto('https://www.scrapingcourse.com/ecommerce/');
    console.log(await page.title());
    
    await browser.close();
};

scraper();
```

Replace `YOUR_ZENROWS_API_KEY` with your actual API key and run the script:

```bash Python theme={"theme":"css-variables"}
python scraper.py
```

```bash Node.js theme={"theme":"css-variables"}
node scraper.js
```

### Expected Output

The script will print the page title:

```plaintext theme={"theme":"css-variables"}
ScrapingCourse.com E-commerce Challenge
```

Perfect! You've just made your first web scraping request with the Zenrows Browser using Playwright.

## 3. Build a Real-World Scraping Scenario

Let's scale up to a practical scraping scenario by extracting product information from the e-commerce site. Using Playwright's powerful selectors and data extraction methods, we'll modify our code to extract product names, prices, and URLs from the page.

```python Python theme={"theme":"css-variables"}
# pip install playwright
import asyncio
from playwright.async_api import async_playwright

# scraping browser connection URL
connection_url = "wss://browser.zenrows.com?apikey=YOUR_ZENROWS_API_KEY"

async def scraper(url):
    async with async_playwright() as p:
        # connect to the scraping browser
        browser = await p.chromium.connect_over_cdp(connection_url)
        page = await browser.new_page()
        
        try:
            await page.goto(url)
            
            # extract the desired data
            await page.wait_for_selector(".product")
            products = await page.query_selector_all(".product")
            data = []
            
            for product in products:
                name = await product.query_selector(".product-name")
                price = await product.query_selector(".price")
                product_url = await product.query_selector(".woocommerce-LoopProduct-link")
                
                data.append({
                    "name": await name.text_content() or "",
                    "price": await price.text_content() or "",
                    "productURL": await product_url.get_attribute("href") or "",
                })
            
            return data
        except Exception as error:
            return error
        finally:
            await page.close()
            await browser.close()

if __name__ == "__main__":
    url = "https://www.scrapingcourse.com/ecommerce/"
    products = asyncio.run(scraper(url))
    print(products)
```

```javascript Node.js theme={"theme":"css-variables"}
// npm install playwright
const { chromium } = require('playwright');

// connection URL
const connectionURL = 'wss://browser.zenrows.com?apikey=YOUR_ZENROWS_API_KEY';

const scraper = async (url) => {
    // connect to the scraping browser
    const browser = await chromium.connectOverCDP(connectionURL);
    const page = await browser.newPage();
    
    try {
        await page.goto(url);
        await page.waitForSelector('.product');
        
        // extract the desired data
        const data = await page.$$eval('.product', (products) =>
            products.map((product) => ({
                name: product.querySelector('.product-name')?.textContent.trim() || '',
                price: product.querySelector('.price')?.textContent.trim() || '',
                productURL: product.querySelector('.woocommerce-LoopProduct-link')?.href || '',
            }))
        );
        
        return data;
    } finally {
        await page.close();
        await browser.close();
    }
};

// execute the scraper function
(async () => {
    const url = 'https://www.scrapingcourse.com/ecommerce/';
    const products = await scraper(url);
    console.log(products);
})();
```

### Run Your Application

Execute your script to test the scraping functionality:

```bash Python theme={"theme":"css-variables"}
python scraper.py
```

```bash Node.js theme={"theme":"css-variables"}
node scraper.js
```

**Example Output**

The script will extract and display product information:

```json theme={"theme":"css-variables"}
[
    {
        "name": "Abominable Hoodie",
        "price": "$69.00",
        "productURL": "https://www.scrapingcourse.com/ecommerce/product/abominable-hoodie/"
    },
    {
        "name": "Artemis Running Short",
        "price": "$45.00",
        "productURL": "https://www.scrapingcourse.com/ecommerce/product/artemis-running-short/"
    }
    // ... more products
]
```

Congratulations! 🎉 You've successfully built a real-world scraping scenario with Playwright and the Zenrows Browser.

## 4. Alternative: Using the Zenrows Browser SDK

For a more streamlined development experience, you can use the Zenrows Browser SDK instead of managing WebSocket URLs manually. The SDK simplifies connection management and provides additional utilities.

> [!NOTE]
>
> The Zenrows Browser SDK is currently only available for JavaScript. For more details, see the [GitHub Repository](https://github.com/ZenRows/browser-js-sdk).

### Install the SDK

```bash Node.js theme={"theme":"css-variables"}
npm install @zenrows/browser-sdk
```

### Quick Migration from WebSocket URL

If you have existing Playwright code using the WebSocket connection, migrating to the SDK requires minimal changes:

**Before (WebSocket URL):**

```javascript Node.js theme={"theme":"css-variables"}
const { chromium } = require('playwright');
const connectionURL = 'wss://browser.zenrows.com?apikey=YOUR_ZENROWS_API_KEY';

const browser = await chromium.connectOverCDP(connectionURL);
```

**After (SDK):**

```javascript Node.js theme={"theme":"css-variables"}
const { chromium } = require('playwright');
const { ScrapingBrowser } = require('@zenrows/browser-sdk');

const scrapingBrowser = new ScrapingBrowser({ apiKey: 'YOUR_ZENROWS_API_KEY' });
const connectionURL = scrapingBrowser.getConnectURL();
const browser = await chromium.connectOverCDP(connectionURL);
```

### Complete Example with SDK

```javascript Node.js theme={"theme":"css-variables"}
// npm install @zenrows/browser-sdk playwright
const { chromium } = require('playwright');
const { ScrapingBrowser } = require('@zenrows/browser-sdk');

const scraper = async () => {
    // Initialize SDK
    const scrapingBrowser = new ScrapingBrowser({ apiKey: 'YOUR_ZENROWS_API_KEY' });
    const connectionURL = scrapingBrowser.getConnectURL();
    
    const browser = await chromium.connectOverCDP(connectionURL);
    const page = await browser.newPage();
    
    await page.goto('https://www.scrapingcourse.com/ecommerce/');
    console.log(await page.title());
    
    await browser.close();
};

scraper();
```

### SDK Benefits

* **Simplified configuration:** No need to manually construct WebSocket URLs
* **Better error handling:** Built-in error messages and debugging information
* **Future-proof:** Automatic updates to connection protocols and endpoints
* **Additional utilities:** Access to helper methods and advanced configuration options

> [!TIP]
>
> The SDK is particularly useful for production environments where you want cleaner code organization and better error handling.

## How Playwright with the Zenrows Browser Helps

Combining Playwright with the Zenrows Browser provides powerful advantages for web scraping:

### Key Benefits

* **Cloud-based browser instances:** Run Playwright scripts on remote Chrome instances, freeing up local resources for other tasks.

* **Seamless integration:** Connect your existing Playwright code to Zenrows with just a WebSocket URL change - no complex setup required.

* **Advanced automation:** Use Playwright's full feature set, which includes page interactions, form submissions, file uploads, and complex user workflows.

* **Built-in anti-detection:** Benefit from residential proxy rotation and genuine browser fingerprints automatically.

* **Cross-browser support:** While we use Chromium for optimal compatibility, Playwright's API remains consistent across different browser engines.

* **High concurrency:** Scale your Playwright scripts with up to 400 concurrent browser instances on Scale, more on Enterprise.

* **Reliable execution:** Cloud infrastructure ensures consistent performance without local browser management overhead.

## Troubleshooting

Below are common issues you might encounter when using Playwright with the Zenrows Browser:

**1. Connection Refused**

If you receive a Connection Refused error, it might be due to:

* **API Key Issues:** Verify that you're using the correct API key.
* **Network Issues:** Check your internet connection and firewall settings.
* **WebSocket Endpoint:** Ensure that the WebSocket URL (`wss://browser.zenrows.com`) is correct.

**2. Empty Data or Timeout Errors**

* Use `page.waitForSelector()` to ensure elements load before extraction

* Increase timeout values for slow-loading pages

  ```javascript scraper.js theme={"theme":"css-variables"}
  await page.goto('https://example.com', { timeout: 60000 });  // 60 seconds
  ```

* Verify CSS selectors are correct using browser developer tools

* Add `page.waitForLoadState('networkidle')` for dynamic content

**3. Browser Context Issues**

* Use existing context when available: `browser.contexts[0] if browser.contexts else await browser.new_context()`
* Properly close pages and browsers to prevent resource leaks
* Handle exceptions properly to ensure cleanup occurs

**4. Geolocation Blocks**

Although Zenrows rotates IPs, some websites may block them based on location. Try adjusting the region or country settings.

> [!NOTE]
>
> For more information, check the Zenrows Browser [Region Documentation](https://docs.zenrows.com/browser-sessions/features/world-region.md) and [Country Documentation](https://docs.zenrows.com/browser-sessions/features/country.md).

**5. Get Help From Zenrows Experts**

Our support team is available to assist you if issues persist despite following these solutions. Use the Zenrows Browser dashboard or [email us](mailto:success@zenrows.com) for personalized help from Zenrows experts.

[Open the Zenrows Browser](https://app.zenrows.com/browser)

## Next Steps

You now have a solid foundation for Playwright-based web scraping with Zenrows. Here are some recommended next steps:

* **[Practical Use Cases](https://docs.zenrows.com/browser-sessions/help/practical-use-cases.md)**: \
  Learn common scraping patterns, including screenshots, custom JavaScript execution, and form handling.
* **[Complete Zenrows Browser Documentation](https://docs.zenrows.com/browser-sessions/introduction.md)**: \
  Explore all available features and advanced configuration options for the Zenrows Browser.
* **[Playwright Web Scraping Guide](https://www.zenrows.com/blog?q=playwright)**: \
  Dive deeper into Playwright techniques for sophisticated scraping scenarios.
* **[Pricing and Plans](https://docs.zenrows.com/first-steps/pricing.md)**: \
  Understand how browser usage is calculated and choose the plan that fits your scraping volume.

## Frequently Asked Questions (FAQ)

> [accordion] Can I use the Zenrows Browser with Puppeteer?
>
> Yes, the Zenrows Browser is compatible with Puppeteer as well. The integration is similar, requiring only a change in the connection method to utilize our WebSocket endpoint.
> \[!TIP] For detailed instructions, refer to our [Puppeteer Integration article](https://docs.zenrows.com/browser-sessions/get-started/puppeteer.md).

> [accordion] Do I need to configure proxies manually with the Zenrows Browser?
>
> No, the Zenrows Browser handles proxy configuration and IP rotation automatically. You don't need to set up proxies manually.

> [accordion] Can the Zenrows Browser solve CAPTCHAs?
>
> Currently, the Zenrows Browser does not support CAPTCHA solving. For handling CAPTCHAs, you may need to use third-party services.
> \[!TIP] Consider using our [Fetch](https://docs.zenrows.com/fetch/api-reference.md) for additional features like CAPTCHA solving, advanced anti-bot bypass, and more.

> [accordion] Can I use all Playwright features with the Zenrows Browser?
>
> Yes! The Zenrows Browser supports the full Playwright API. You can use page interactions, screenshots, PDF generation, network interception, and all other Playwright features seamlessly.

> [accordion] How do I handle multiple pages or tabs?
>
> You can create multiple pages within the same browser context using `await browser.newPage()` or `await context.newPage()`. Each page operates independently while sharing the same browser session.

> [accordion] Can I use Playwright's built-in retry mechanisms?
>
> Absolutely! Playwright's `expect()` assertions, `waitForSelector()`, and other built-in retry mechanisms work perfectly with the Zenrows Browser. These features help handle dynamic content and improve scraping reliability.

> [accordion] How do I take screenshots with Playwright and the Zenrows Browser?
>
> Use Playwright's standard screenshot methods:
>
> ```python theme={"theme":"css-variables"}
>     await page.screenshot(path='screenshot.png')
> ```
>
> The screenshot will be saved locally while the browser runs in the cloud.

> [accordion] Can I use Playwright's network interception features?
>
> Yes! You can intercept requests, modify responses, and monitor network traffic using Playwright's `page.route()` and `page.on('request')` methods with the Zenrows Browser.

> [accordion] What's the difference between using Playwright locally vs. with the Zenrows Browser?
>
> The main difference is that the browser runs in Zenrows' cloud infrastructure instead of locally. This provides better IP rotation, fingerprint management, and resource efficiency while maintaining the exact same Playwright API.

> [accordion] How do I handle file downloads with Playwright and the Zenrows Browser?
>
> File downloads work with Playwright's standard download handling. Use `page.waitForDownload()` and the download will be transferred from the cloud browser to your local environment automatically.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.