Clean Browser Automation

I try not to pollute my machine with libraries and apps due to my experiments, so I cannot do without Homebrew and Docker. Here’s how I quickly set up an isolated environment for some dirty “browser automation” I needed 😉

https://github.com/SeleniumHQ/docker-selenium

Good quick start guide. As there is no selenium for M1/arm yet, it errors. Adding the platform (and an optional name) works wonders.

projects % docker run -d -p 4444:4444 -p 7900:7900 --shm-size="2g" selenium/standalone-firefox:4.1.1-20211217 
WARNING: The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested

projects % docker run -d -p 4444:4444 -p 7900:7900 --shm-size="2g" --platform linux/amd64 --name selfox selenium/standalone-firefox:4.1.1-20211217
ce4ee1ba7b31c59b7c9964abd1c219b87a4ab49098fb4436dd0a1ba797a6896b

As mentioned in the quick start, browse to http://localhost:4444/ to check your sessions and http://localhost:7900/ for VNC to look at the browser.

For the code, here’s Kotlin-in-a-script:

import org.openqa.selenium.*
import org.openqa.selenium.firefox.FirefoxOptions
import org.openqa.selenium.remote.RemoteWebDriver
import java.net.URL

fun WebDriver.f(selector: String): WebElement = this.findElement(By.cssSelector(selector))

fun main() {
    val driver = RemoteWebDriver(URL("http://localhost:4444"), FirefoxOptions())
    try {
        driver.get("https://www.google.com")
        val text = driver.f("input[name=btnI]").getAttribute("value")
        println(text)
    } finally {
        driver.quit()
    }
}

Now I can destroy, recreate and reuse it for other projects easily.