DEV Community

Cover image for I got tired of bot detection in automation testing, so I wrote this 4-line Python fix
Dhiraj Das
Dhiraj Das

Posted on • Originally published at dhirajdas.dev

I got tired of bot detection in automation testing, so I wrote this 4-line Python fix

It happened again.

My script was perfect locally. I pushed it to CI/CD, and... 403 Forbidden. I wasn't testing a bank; I was testing a landing page. The modern web has become hostile to automation.

Developers are tired of getting blocked by Cloudflare Turnstiles, and "Verify you are human" loops when using Selenium or Playwright. We spend more time fighting bot detection than writing actual tests.

The Old Way (The Struggle)

We've all been there. You try to make Selenium "stealthy" by piling on options, changing user agents, and praying.


python
# The "Please don't ban me" starter pack
options = webdriver.ChromeOptions()
options.add_argument("--headless") # <--- This gets you banned instantly on many sites
options.add_argument("--disable-blink-features=AutomationControlled")
options.add_argument("user-agent=Mozilla/5.0...")
# ... 20 more lines of hoping it works
driver = webdriver.Chrome(options=options)

# Result: Still blocked.
The New Way (The 4-Line Fix)
I built sb-stealth-wrapper to solve this once and for all. It wraps SeleniumBase's UC Mode with intelligent defaults that just work.

Python

from sb_stealth_wrapper import StealthBot

# 1. Initialize (Automatically handles Linux/Xvfb stealth)
with StealthBot(headless=True) as bot:

    # 2. Navigate safely (Proactively checks for challenges)
    bot.safe_get("[https://nowsecure.nl](https://nowsecure.nl)")

    # 3. Verify success
    bot.save_screenshot("passed.png")
The Secret Sauce: Why it Works
1. The Linux/Xvfb Hack
Headless Chrome on Linux is a dead giveaway. It screams "I am a bot" because it lacks a display server.

My wrapper detects if it's running on Linux and automatically spawns a Virtual Display (Xvfb). This means Chrome thinks it has a real monitor, giving you the stealth of a headed browser with the convenience of a headless server.

2. Heuristic Clicking
bot.click() is too perfect. It's instantaneous and mechanical.

bot.smart_click() is different. It scrolls the element into view, hovers for a split second, and then clicks using Bezier curves (human-like mouse movement). If the element is obscured by a CAPTCHA, it intelligently detects the frame and handles it.

The Live Demo (Production Ready)
Real-world automation requires error handling. We don't just want to "open" the page; we want to prove we beat the bot protection.

Here is a robust script using sb-stealth-wrapper. It navigates to nowsecure.nl, verifies the success message, and grabs debug info if anything fails.

Python

from sb_stealth_wrapper import StealthBot

if __name__ == "__main__":
    # 1. Initialize (Auto-handles Xvfb/Headless)
    with StealthBot(headless=True) as bot:

        print("--- Testing Protected Site (nowsecure.nl) ---")
        bot.safe_get("[https://nowsecure.nl](https://nowsecure.nl)")

        # 2. Verify we passed the challenge
        try:
            # We wait for the success header (Note: The text changed from "OH YEAH" recently)
            bot.sb.wait_for_text("NOWSECURE", "h1", timeout=30)
            print("✅ SUCCESS: Bypassed Cloudflare/Turnstile!")
            bot.save_screenshot("success_proof")

        except Exception as e:
            print(f"❌ FAILURE: Detection triggered. Error: {e}")

            # 3. Auto-Debug (Saves HTML so you can see why it failed)
            with open("debug_failure.html", "w", encoding="utf-8") as f:
                f.write(bot.sb.get_page_source())
            print("Dumped page source to debug_failure.html")

    print("Test Complete.")
Get It Now
Stop writing boilerplate. Start writing tests.

Bash

pip install sb-stealth-wrapper
You can check out the source code and documentation here:

GitHub: https://github.com/godhiraj-code/stealthautomation

PyPI: https://pypi.org/project/sb-stealth-wrapper/

❤️ Standing on the Shoulders of Giants
This project wouldn't exist without the incredible work done by the SeleniumBase team.

sb-stealth-wrapper is essentially a love letter to their engineering on UC Mode. I simply wrapped their robust engine in a way that makes it "plug-and-play" for specific CI/CD use cases. If you like my wrapper, please go give SeleniumBase a Star on GitHub—they deserve all the credit for the heavy lifting.

Ethical Disclaimer: This tool is for educational purposes and for testing environments you own. Do not use it for unauthorized scraping or bypassing security controls on websites you do not have permission to test.
Enter fullscreen mode Exit fullscreen mode

Top comments (0)