Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium + Go - how to?

Tags:

go

I'm starting to take a look on Selenium with Go language, but I didn't find too much info. I'm using github.com/tebeka/selenium.

In Python, I just install (pip install selenium) and code like this to open a browser:

from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')
driver.get('http://www.hp.com')

How do I do the same in Go? I'm trying this, but it does not open the browser like Python does:

package main
import (
    "fmt"
    "github.com/tebeka/selenium"
)

func main() {
    selenium.ChromeDriver("./chromedriver.exe")
    caps := selenium.Capabilities{"browserName": "chrome"}
    selenium.NewRemote(caps, fmt.Sprintf("http://www.google.com", 80))
}

Is there a simple way in go to just open the browser in my machine like that 3 Python lines do? Thanks!

like image 436
Gustavo Avatar asked Sep 01 '25 01:09

Gustavo


1 Answers

In python selenium, it automatically starts the browser while Golang doesn't. You have to run the browser (service) explicitly. This is a simple example of using Chromedriver with Golang.

package main

import (
    "github.com/tebeka/selenium"
    "github.com/tebeka/selenium/chrome"
)

func main() error {
    // Run Chrome browser
    service, err := selenium.NewChromeDriverService("./chromedriver", 4444)
    if err != nil {
        panic(err)
    }
    defer service.Stop()

    caps := selenium.Capabilities{}
    caps.AddChrome(chrome.Capabilities{Args: []string{
        "window-size=1920x1080",
        "--no-sandbox",
        "--disable-dev-shm-usage",
        "disable-gpu",
        // "--headless",  // comment out this line to see the browser
    }})

    driver, err := selenium.NewRemote(caps, "")
    if err != nil {
        panic(err)
    }

    driver.Get("https://www.google.com")
}
like image 188
Henry Kim Avatar answered Sep 03 '25 20:09

Henry Kim