How to Install and Use Stagehand for Streamlined Browser Automation ๐
Monday, Dec 23, 2024 | 7 minute read
Revolutionizing browser automation, this innovative framework boosts developer productivity with AI-driven features, seamless natural language interaction, a friendly API, and active community support, making complex tasks effortless and efficient. ๐๐ปโจ
โAdvancements in technology often stem from the need to solve human pain points.โ ๐
In this fast-paced digital age, developers are facing increasingly complex challenges in web automation! They urgently need effective and convenient tools to enhance their productivity and cut down on time-wasting tasks. To address these pain points, a project called Stagehand has emerged! โจ
Stagehand is an innovative automation framework focused on simplifying the web automation process, leveraging cutting-edge artificial intelligence technologies to save developers time and effort. It is built on the open-source Playwright project, and aims to significantly improve the user experience in browser automation tasks, allowing developers to interact with the framework using natural language. What a clever idea! ๐ป๐
Letโs dive into the world of Stagehand and see how this trendsetting open-source project is changing developersโ lives with its innovative design! ๐
1. Stagehand: A Whole New Automation Experience ๐
Stagehand is an outstanding web browsing framework that harnesses the power of artificial intelligence to enhance developer productivity by simplifying web automation tasks! ๐ผ This framework not only inherits the excellent features of Playwright but also offers a natural language-based interface, making interactions with the browser feel seamless for all developers! Its user-focused design allows you to effortlessly command the framework to carry out automation tasks. ๐
2. Key Features: What Sets Stagehand Apart โจ
- User-Friendly API ๐: Stagehand presents three core APIs:
act
,extract
, andobserve
, which greatly simplify browser operations and lower the barrier for usage! Every developer can quickly get started and enjoy web automation with ease! ๐ - Multi-Language Model Support ๐: Stagehand supports various language models, allowing developers to flexibly write and execute automation scripts based on their needs, significantly enhancing usability and flexibility! ๐ค
- Community Engagement ๐ฌ: As an early-released tool, Stagehand actively encourages users to provide feedback through Slack, meaning it continually grows through improvements and optimizations โ itโs truly a โsmartโ tool! ๐ฑ
3. Developers’ Top Choice: The Real Reasons Behind Stagehand ๐
- Simplified Automation Review Applications ๐ ๏ธ: Stagehand’s design enables developers to perform tasks efficiently, making automation reviews in modern frontend applications easier than ever, and strongly recommends it for every developer! ๐
- Seamless Integration with AWS โ๏ธ: By leveraging AWS’s robust infrastructure, Stagehand can automate handling live changes. For instance, automating the deployment and management of new code through GitHub Actions saves developers an immense amount of time! โณ
- Fast Deployment and Management of Review Applications ๐: Whenever a new pull request is created on GitHub, Stagehand intelligently creates the corresponding review application and generates new instances with each change submission. These ephemeral yet complete applications effectively simulate real production environments, enabling developers to intuitively test and validate features! ๐
Overview of the Workflow ๐
- Users open a pull request, automatically triggering the creation of the review application. ๐
- As new code is submitted, new review application instances will be generated. ๐
- A customizable dashboard will be created in the GitHub repository, allowing developers to manage access rights and view the status and progress of their review applications in real-time! ๐
AWS Infrastructure โ๏ธ
During execution, Stagehand utilizes the following AWS services to amplify its capabilities:
- S3 Bucket ๐ฆ: Used for storing review application data, ensuring data persistence and availability, making data security no longer a concern.
- CloudFront ๐: Handles requests from users and caches resources, improving access efficiency and elevating the user experience.
- IAM ๐: Securely manages access credentials, ensuring the safety of both data and applications, so developers can use it with confidence!
- CloudFormation ๐ ๏ธ: Simplifies infrastructure management through templating, helping developers easily build and manage necessary resources โ itโs simply fantastic!
Future Developments ๐
The future developments of Stagehand are equally exciting, including:
- Creating new dashboard templates to enhance user experience, delivering more surprises! ๐
- Expanding support for other cloud service providers to accommodate a broader range of user needs โ itโs truly a user-friendly project! โ๏ธ
- Enhancing automation testing capabilities to perform even better across multi-cloud infrastructures, promoting more effective automation testing! ๐
Installing Stagehand ๐
To get started with Stagehand, ensure you have Node.js and npm installed. Next, weโll install it using the command line, simply run the following command in your terminal:
npm install @browserbasehq/stagehand zod
Explanation: This command installs both the Stagehand framework and its dependency library Zod. โญ๏ธ @browserbasehq/stagehand
is our core library, while zod
is used for data validation, ensuring that the data we extract meets the expected structure. Make sure to run this command in your projectโs root directory for proper installation!
Setting Up Environment Variables ๐ ๏ธ
Before using Stagehand, you need to set some environment variables for easy API service connections. Enter the following command in your terminal, remembering to replace the placeholders with your own API keys:
export OPENAI_API_KEY=sk-...
export ANTHROPIC_API_KEY=sk-...
Next, set up the BROWSERBASE_API_KEY and BROWSERBASE_PROJECT_ID:
export BROWSERBASE_API_KEY=...
export BROWSERBASE_PROJECT_ID=...
Explanation: These environment variables will allow Stagehand to call the relevant APIs. ๐ก OPENAI_API_KEY
and ANTHROPIC_API_KEY
serve as credentials for connecting to AI services, while BROWSERBASE_API_KEY
and BROWSERBASE_PROJECT_ID
are the necessary credentials for accessing Browserbase, ensuring a smooth operation!
Installing Playwright ๐
Since Stagehand relies on Playwright to control the browser, you need to ensure Playwright is installed:
npm exec playwright install
Explanation: Running this command will automatically download and install the required browser drivers, allowing Stagehand to soar through the designated browsers! ๐ฉโ๐ป Playwright supports multiple browsers like Chrome and Firefox, so you can pick based on your preferences!
Creating a Stagehand Instance ๐งฐ
Creating a Stagehand instance is the first step to using this tool, configuring instances based on different environments. Hereโs an example of code for a local environment:
import { Stagehand } from "@browserbasehq/stagehand";
import { z } from "zod";
// Create a Stagehand instance, setting the environment to LOCAL
const stagehand = new Stagehand({
env: "LOCAL", // Using local environment
});
Explanation: In this code, we first import Stagehand
and Zod
. ๐ We create an instance named stagehand
and set the env
option to LOCAL
so that we can better conduct all operations.
Initializing Stagehand ๐
Before you start performing any web actions, itโs essential to initialize your Stagehand instance, so it is prepared to accept various commands:
await stagehand.init(); // Initialize Stagehand instance
Explanation: Calling the init
method executes the initialization process, ensuring all settings are ready. โ๏ธ This usually takes some time to complete, so we use await
to wait for it to finishโpatience is key!
Operating on Web Pages ๐
Once initialized, you can begin operating on web pages! For example, navigating to a URL and clicking an element. Below is an example of such an operation:
// Navigate to the GitHub Stagehand page
await stagehand.page.goto("https://github.com/browserbase/stagehand");
// Perform a click action, such as clicking on contributors
await stagehand.act({ action: "click on the contributors" });
Explanation: First, we use the goto
method to navigate to the specified GitHub page, then call the act
method to perform the click action and simulate user interaction on the page. ๐ Here, we clicked on “contributors” to gather more information quickly and easily!
Data Extraction ๐
Stagehand makes extracting necessary data from the page extremely straightforward. The following example shows how to extract information about top contributors:
// Extract information about contributors
const contributor = await stagehand.extract({
instruction: "extract the top contributor",
schema: z.object({
username: z.string(), // Username must be a string
url: z.string(), // URL must also be a string
}),
});
Explanation: In this code, we utilize the extract
method to pull data from the page. ๐ By providing an instruction
field, we tell Stagehand what information we want to retrieve, and using schema
, we normalize the data structure to ensure the returned data meets our predefined conditions.
Closing Stagehand โ
After completing all operations, donโt forget to close Stagehand to free up resources and avoid memory waste:
await stagehand.close(); // Close Stagehand instance
Explanation: Calling the close
method is a good practice, ensuring that relevant resources are promptly closed after operations conclude. ๐ This helps prevent potential memory leaks and keeps the program robust and reliable!
Logging ๐
Stagehand also provides logging functionality, which is very helpful for debugging and monitoring. The following example illustrates how to log messages:
stagehand.log("Hello, world!"); // Log a message
Explanation: By using the log
method, you can record custom messages that make it easier to trace issues while debugging. โจ Once logs are outputted, you’ll gain a clearer understanding of each step in your program’s execution, helping you troubleshoot effectively and keep moving forward!