Browser Automation with Code: A Practical Guide
In this article
Browser automation lets you script repetitive web tasks—filling forms, scraping data, or testing your own site—using code. This guide covers the core practices that make automation robust: choosing the right tool, writing resilient selectors, handling waits correctly, and debugging failures. You’ll need basic programming knowledge (any language) and a code editor. No prior automation experience required.
What You'll Need
- A computer with internet access
- A code editor (VS Code, Sublime Text, or similar)
- Node.js (if using Playwright or Puppeteer) or Python (if using Selenium)
- Basic understanding of HTML/CSS selectors
- A test website you’re allowed to automate (your own or a public sandbox)
Step-by-Step
- Choose your automation tool. For most modern web apps, Playwright (Node.js/Python) is the best balance of speed and reliability. Puppeteer is similar but Chromium-only. Selenium is older but supports more browsers. Start with Playwright if you’re new.
- Install the tool. For Playwright with Node.js: run
npm init -ythennpm install @playwright/test. Then install browsers withnpx playwright install. For Python:pip install playwrightandplaywright install. - Write a basic script. Create a file (e.g.,
test.spec.jsfor Playwright). Start with a simple navigation: - Use explicit waits instead of fixed sleeps. Always wait for elements to be ready before interacting. In Playwright, use
await page.waitForSelector('#submit')or rely on auto-waiting actions likeclick(). AvoidsetTimeout()—it’s fragile. - Prefer robust selectors. Use CSS selectors that are stable: prefer IDs, data-testid attributes, or text content over fragile class names that change often. Example:
button[data-testid="login"]is better than.btn-primary. - Handle iframes and popups. If your target site uses iframes, switch context with
page.frameLocator('iframe').locator(...). For popups, listen for the popup event and interact with the new page object. - Take screenshots on failure. Wrap your steps in try/catch and capture a screenshot when an error occurs. This helps debugging enormously.
- Run tests headless by default. Headless mode (no visible browser) is faster and more stable for CI. But run headed (
headless: false) when debugging to see what’s happening. - Use environment variables for secrets. Never hardcode passwords or tokens. Use
process.env.LOGIN_PASSWORDor a config file that’s gitignored. - Test on multiple browsers. Playwright can run the same script on Chromium, Firefox, and WebKit. This catches browser-specific issues.
Common Mistakes
- Using sleeps instead of waits. Fixed delays break when the network is slow or fast. Always use explicit waits.
- Selecting elements by brittle CSS classes. Classes like
.activeor.btnchange often. Use stable attributes or text. - Ignoring element visibility. An element might exist in DOM but be hidden. Use
toBeVisible()checks or wait for it to be actionable. - Not handling multiple tabs/windows. If your script opens a new tab, you must switch to it explicitly.
- Running without error handling. Unhandled exceptions stop the script silently. Always catch and log errors.
Tips
- Start with a small script. Automate one action (like logging in) before building a full workflow.
- Use data-testid attributes. If you control the site, add
data-testidto elements you want to automate—it’s the most stable selector. - Record and replay. Playwright’s codegen (
npx playwright codegen) lets you record actions and generates the script. Use it as a starting point, then refine. - Keep selectors in one place. Define them as constants at the top of your file so you can update them easily.
- Use headless mode for CI, headed for debugging. You’ll save time in the long run.
Troubleshooting
- Element not found: Check if the page loaded fully. Increase wait time or use
waitForSelectorwith a longer timeout. Also check if the element is inside an iframe or shadow DOM. - Script works locally but fails in CI: CI runs headless and often on a different OS. Ensure you installed browsers for the CI environment. Also, avoid absolute paths.
- Click doesn’t work: The element might be covered by another element. Use
element.click({force: true})as a last resort, but first check if the element is actually visible. - Network errors: Retry logic can help. Use
page.waitForLoadState('networkidle')but be cautious—some sites never go idle. Better to wait for a specific element. - Browser crashes: Update your browser and the automation library. Also, running too many parallel tests can cause memory issues—limit concurrency.
Frequently Asked Questions
Can I automate any website?
Technically yes, but you must follow the site’s terms of service and robots.txt. Automating login or scraping may be prohibited. Always get permission for sites you don’t own.
What’s the difference between Selenium and Playwright?
Selenium is older, supports more browsers, and has a larger community. Playwright is faster, has better auto-waiting, and a simpler API. For new projects, Playwright is often recommended.
Do I need to know HTML to automate browsers?
Yes, basic knowledge of HTML and CSS selectors is essential to locate elements. You’ll also need to understand the DOM structure of the pages you’re automating.
How do I handle CAPTCHAs?
You shouldn’t try to bypass CAPTCHAs—it’s often against terms of service and can be illegal. Instead, design your automation to avoid triggering them (e.g., slow down, use real user agents) or use a service that provides human-solving if you have permission.
Can I run automation on a schedule?
Yes, you can use cron jobs (Linux/macOS) or Task Scheduler (Windows) to run your script at set times. Alternatively, use CI tools like GitHub Actions to trigger runs.
What if the site changes its layout?
Your selectors may break. That’s why you should keep selectors centralized and update them quickly. Also, use robust attributes like data-testid to minimize breakage.