User Agents

Web browsers and everyday web tech, explained

Build an AI Scraper with Browser MCP and Browserless BQL

· 6 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Building an AI-powered scraper using the Model Context Protocol (MCP) and Browserless BQL (Browser Query Language) allows you to extract structured data from websites using natural language prompts rather than writing complex CSS selectors or XPath queries. This setup bridges the gap between a Large Language Model (LLM) and a headless browser, enabling the LLM to "see" the page and execute precise data extraction queries through a standardized protocol. By leveraging BQL, you can treat a website like a database, querying specific elements based on their semantic meaning or structural position without needing to manually inspect the DOM for every single page change.

What You'll Need

  • An MCP-compatible Client: A tool or environment that supports the Model Context Protocol (such as Claude Desktop or a custom MCP host).
  • Browserless.io Account: An active account to access the Browserless platform and obtain an API key.
  • Browser MCP Server: The specific MCP server implementation designed to interface with browser automation tools.
  • Node.js and npm: Installed on your local machine to run and configure the MCP server.
  • Basic Knowledge of JSON: Since the communication between the LLM, the MCP server, and Browserless happens via JSON payloads.

Step-by-Step

  1. Set Up Your Browserless Environment: Create an account at Browserless.io. Once logged in, locate your API key from the dashboard. This key is essential for authenticating your requests and ensures that your scraper has a dedicated headless browser instance to execute commands. Note the WebSocket URL provided by Browserless, as this is where the MCP server will send its instructions.
  2. Install the Browser MCP Server: Clone or install the Browser MCP server repository to your local machine. Use npm to install the necessary dependencies. The MCP server acts as the middleman; it translates the LLM's high-level intent (e.g., "Find all product prices on this page") into a BQL query that Browserless can understand. Ensure your environment variables are configured with your Browserless API key.
  3. Configure the MCP Client: Open your MCP-compatible client's configuration file (e.g., `claude_desktop_config.json`). Add the browser server to the list of configured servers. You will need to specify the command to run the server (usually `node`) and the path to the server's entry point. Restart the client to ensure the new tools are loaded and available for the LLM to call.
  4. Define the Scraping Target: Provide the LLM with the URL of the website you wish to scrape. Instead of writing a script, you will now use a natural language prompt. For example, tell the LLM: "Use the browser tool to navigate to [URL] and extract a list of all article titles and their corresponding links."
  5. Crafting the BQL Query: The LLM will generate a BQL (Browser Query Language) request. BQL allows for powerful selection logic. For instance, instead of a fragile selector like `div.main > ul > li:nth-child(2) > a`, BQL can target elements based on attributes or content patterns. The MCP server sends this BQL query to Browserless, which executes it within the headless browser.
  6. Handling Dynamic Content: If the website uses heavy JavaScript or infinite scrolling, instruct the LLM to perform specific actions before extracting data. You can tell the LLM to "scroll to the bottom of the page three times" or "click the 'Load More' button until no more results appear." The MCP server will translate these into browser actions before the final BQL extraction occurs.
  7. Structuring the Output: Once the data is retrieved via BQL, it returns as a JSON array. Instruct the LLM to format this data into your desired final structure, such as a CSV table, a Markdown list, or a specific JSON schema. This step ensures that the raw scraped data is cleaned and usable for your specific application.
  8. Testing and Iteration: Run a few test queries on different pages of the site to ensure the BQL selectors are robust. If the LLM misses certain elements, refine your prompt to be more specific about where the data is located or what labels are associated with the target information.

Common Mistakes

One of the most frequent errors is failing to account for the asynchronous nature of page loading. Users often attempt to run a BQL query immediately after a navigation command, resulting in an empty dataset because the DOM has not yet fully rendered. Always ensure there is a "wait" period or a check for a specific element's visibility before triggering the extraction.

Another common pitfall is over-reliance on the LLM to guess the page structure without providing enough context. While BQL is powerful, providing the LLM with a small snippet of the page's HTML (using a "get HTML" tool first) significantly improves the accuracy of the generated BQL queries. Without this, the LLM may hallucinate selectors that do not exist on the actual page.

Many users also forget to handle pagination. A single BQL query only extracts data from the current view. To scrape an entire site, you must build a loop where the LLM identifies the "Next" button, clicks it, waits for the load, and then repeats the BQL extraction process.

Tips

To maximize efficiency, use BQL's ability to filter data at the browser level. Instead of pulling all text from a page and asking the LLM to filter it (which consumes tokens), write your BQL query to only return the specific fields you need. This reduces latency and lowers the cost of LLM processing.

Implement "User-Agent" rotation if you are scraping sites with strict bot detection. Browserless provides options to customize the browser fingerprint. Ensure your MCP server is configured to pass these headers to avoid being blocked by Cloudflare or similar services.

For complex sites, use a multi-step approach: first, use the browser to take a screenshot or get a simplified accessibility tree. Feed this back to the LLM so it can visually or structurally understand the layout before it writes the final BQL query. This "look-then-act" workflow drastically reduces errors in data extraction.

Troubleshooting

If the MCP server fails to connect to Browserless, first verify your API key and ensure there are no trailing spaces in your configuration file. Check the server logs for "401 Unauthorized" errors, which indicate an authentication failure, or "429 Too Many Requests," which means you have hit your Browserless plan limit.

When the BQL query returns no results despite the element being visible in a standard browser, check for iframes. BQL queries typically operate on the main document. If the data is inside an iframe, you must first instruct the browser to switch context to that specific iframe before executing the query.

If the LLM keeps generating invalid BQL syntax, provide it with a few examples of successful BQL queries in the system prompt. This "few-shot prompting" helps the model understand the exact syntax required by the Browserless engine, reducing the need for repeated trial-and-error iterations.

Frequently Asked Questions

What is the difference between BQL and CSS selectors?

CSS selectors are static paths to elements. BQL is a higher-level query language that allows for more flexible, semantic, and programmatic selection of data, often allowing for filtering and transformation within the query itself.

Does this method work on Single Page Applications (SPAs)?

Yes, because Browserless runs a full headless browser (Chromium), it executes JavaScript exactly like a normal browser would, making it ideal for React, Vue, or Angular applications.

Can I run this entirely locally?

The MCP server and client run locally, but Browserless is a cloud service. To run everything locally, you would need to host your own Browserless Docker container and point your MCP server to the local IP address.

How does MCP improve the scraping process?

MCP standardizes how the LLM interacts with the browser. Instead of writing a custom API wrapper for every project, you use a universal protocol that allows the LLM to discover and use browser tools dynamically.

Is BQL faster than traditional scraping?

In terms of development time, yes, because you don't have to manually find selectors. In terms of execution, it is comparable to traditional headless browser scraping, as it still relies on a Chromium instance.

How do I handle CAPTCHAs with this setup?

Browserless offers integrated CAPTCHA solving services. You can enable these in your Browserless dashboard, and the browser instance will automatically attempt to solve challenges during the MCP session.