Skip to content

Integrating browser-use with Undetected-Chromedriver, Gemini, ML, and Crypto Dice Automation

Integrating browser-use with Undetected-Chromedriver, Gemini, and Machine Learning

Browser automation has come a long way, but avoiding detection while using automation frameworks like Playwright, Selenium, or Puppeteer remains a challenge. In this post, we explore how to integrate browser-use with undetected-chromedriver, Google's Gemini AI, machine learning models, and crypto dice automation for bot-resistant web interactions.


Why Use browser-use with Undetected-Chromedriver?

Traditional browser automation tools can be detected easily, especially on sites with strong bot protection. By integrating undetected-chromedriver, we can bypass bot detection mechanisms while leveraging Playwright’s robust automation capabilities.


Step 1: Modify the browser-use Code to Use Undetected-Chromedriver

To enable bot-resistant browsing, modify browser.py in your browser-use repository with the following implementation:

async def _setup_undetected_browser(self, playwright: Playwright) -> PlaywrightBrowser:
    """Sets up and returns a Playwright Browser instance with anti-detection measures using undetected-chromedriver."""
    try:
        import undetected_chromedriver as uc
        from selenium import webdriver

        options = uc.ChromeOptions()
        options.headless = self.config.headless
        for arg in [
            '--no-sandbox',
            '--disable-infobars',
            '--disable-popup-blocking',
            '--no-first-run',
            '--no-default-browser-check'
        ] + self.disable_security_args + self.config.extra_chromium_args:
            options.add_argument(arg)

        if self.config.proxy:
            options.add_argument(f'--proxy-server={self.config.proxy.get("server")}')

        driver = uc.Chrome(options=options)  # type: ignore
        cdp_endpoint = driver.command_executor._url + '/devtools/browser/' + driver.session_id  # type: ignore
        browser = await playwright.chromium.connect_over_cdp(cdp_endpoint)

        # Ensure Selenium driver quits when Playwright browser closes
        def _close_undetected_chrome(self):
            try:
                driver.quit()
            except Exception as e:
                logger.warn(f"Error quitting undetected_chromedriver: {e}")

        browser._close_undetected_chrome = self._close_undetected_chrome  # type: ignore
        return browser

    except ImportError:
        logger.error("undetected-chromedriver is not installed. Install it with `pip install undetected-chromedriver`.")
        raise
    except Exception as e:
        logger.error(f"Failed to launch undetected-chromedriver: {e}")
        raise

This implementation ensures the browser runs stealthily and minimizes detection.


Step 2: Modify the Close Method for Clean Browser Shutdown

Add the following method to properly close the browser and avoid resource leaks:

async def close(self):
    """Close the browser instance."""
    try:
        if self.playwright_browser:
            if hasattr(self.playwright_browser, '_close_undetected_chrome') and self.playwright_browser._close_undetected_chrome:  # type: ignore
                self.playwright_browser._close_undetected_chrome()  # type: ignore

            await self.playwright_browser.close()
        if self.playwright:
            await self.playwright.stop()
    except Exception as e:
        logger.debug(f'Failed to close browser properly: {e}')
    finally:
        self.playwright_browser = None
        self.playwright = None

Step 3: Implement Browser Setup Selection

Ensure that the browser initialization method can properly select undetected-chromedriver:

async def _setup_browser(self, playwright: Playwright) -> PlaywrightBrowser:
    """Sets up and returns a Playwright Browser instance."""
    try:
        if self.config.cdp_url:
            return await self._setup_cdp(playwright)
        if self.config.wss_url:
            return await self._setup_wss(playwright)
        elif self.config.chrome_instance_path:
            return await self._setup_browser_with_instance(playwright)
        elif self.config.use_undetected_chromedriver:
            return await self._setup_undetected_browser(playwright)
        else:
            return await self._setup_standard_browser(playwright)

    except Exception as e:
        logger.error(f'Failed to initialize Playwright browser: {str(e)}')
        raise

Step 4: Run a Sample Script to Test It

Once your modified browser-use setup is complete, use the following script to test bot-resistant browsing:

import asyncio
from browser_use import Agent, Browser, BrowserConfig

async def main():
    config = BrowserConfig(headless=False, use_undetected_chromedriver=True)
    browser = Browser(config=config)
    playwright_browser = await browser.get_playwright_browser()
    context = await playwright_browser.new_context()
    page = await context.new_page()
    await page.goto("https://nowsecure.nl")  # Site to test bot detection
    await asyncio.sleep(5)  # Observe results
    await browser.close()

if __name__ == "__main__":
    asyncio.run(main())

Step 5: Expanding with Machine Learning and AI

Now that we have a bot-resistant browser, let's explore how to integrate Gemini AI and machine learning to enhance automation.

Using Gemini for Text-Based Automation

If you're automating interactions that require AI-generated content, you can integrate Google's Gemini AI:

from google.generativeai import Gemini

# Initialize Gemini AI
gemini = Gemini(api_key="your_gemini_api_key")

async def generate_ai_response(prompt):
    response = gemini.complete(prompt=prompt)
    return response['choices'][0]['text']

Crypto Dice Automation

For crypto dice betting, you can use your automated browser to interact with betting sites:

async def play_crypto_dice():
    page = await browser.new_page()
    await page.goto("https://crypto-dice-betting-site.com")

    # Example: Place a bet
    await page.click("button#bet")
    await page.wait_for_timeout(2000)  # Wait for result

    result = await page.inner_text("div#result")
    print(f"Dice Result: {result}")

    await page.close()

Frequently Asked Questions (FAQ)

Q: What makes undetected-chromedriver useful?
A: It bypasses bot detection, making it useful for web scraping, automation, and avoiding anti-bot systems.

Q: Does this work with proxies?
A: Yes, you can configure proxy-server options in the browser configuration.

Q: How can I integrate machine learning?
A: You can use models like TensorFlow, Gemini AI, or OpenAI’s GPT-4 for decision-making within the automation workflow.


Final Thoughts

With browser-use, undetected-chromedriver, machine learning, and crypto automation, we unlock a powerful bot-resistant automation pipeline. Whether you're working with Gemini AI, web scraping, or crypto gambling automation, this setup enables high stealth and flexibility.

🔥 Let me know in the comments how this setup works for you or if you have any improvements! 🚀


Created 2025-02-15, Updated 2025-02-15
Authors: Harminder Singh Nijjar (2)

Comments