selenium

package module
v0.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2026 License: MIT Imports: 24 Imported by: 0

README

Selenium / WebDriver client for Go (maintained fork)

Language: English | 简体中文

Module github.com/zninggo/selenium
Upstream tebeka/selenium (largely unmaintained since ~2021)
Status Self-use first; public best-effort
Latest v0.11.1
Notable delta ChromeDriver 115+ / W3C find & SendKeys / Selenium 4 service / CDP / HTTP reliability / multi-OS driver download / smoke + optional browser CI

Go Reference CI

This is a WebDriver client for Go. It supports the WebDriver protocol and works with ChromeDriver, Geckodriver, and Selenium server (3 and 4).

This repository is a maintained fork of tebeka/selenium. Upstream commits may be cherry-picked as needed; there is no automatic merge of upstream/master.

Installing

go get github.com/zninggo/selenium@latest

Requires Go 1.22+ and a working WebDriver stack (browser + driver, or Selenium server).

Migrating from tebeka/selenium
  1. Rewrite imports: github.com/tebeka/seleniumgithub.com/zninggo/selenium
  2. go get github.com/zninggo/selenium@v0.11.1
  3. go mod tidy
ChromeDriver (direct, ChromeDriver 115+)

ChromeDriver serves sessions at the root URL — do not append /wd/hub.

package main

import (
	"fmt"

	"github.com/zninggo/selenium"
	"github.com/zninggo/selenium/chrome"
)

func main() {
	const (
		chromeDriverPath = "chromedriver" // or path from vendor/init.go
		port             = 9515
	)

	svc, err := selenium.NewChromeDriverService(chromeDriverPath, port)
	if err != nil {
		panic(err)
	}
	defer svc.Stop()

	caps := selenium.Capabilities{"browserName": "chrome"}
	caps.AddChrome(chrome.Capabilities{
		Args: []string{"--headless=new", "--no-sandbox"},
		W3C:  true,
	})

	// Root URL — not http://127.0.0.1:9515/wd/hub
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d", port))
	if err != nil {
		panic(err)
	}
	defer wd.Quit()

	if err := wd.Get("https://golang.org"); err != nil {
		panic(err)
	}
	fmt.Println(wd.Title())
}

Also see ExampleChromeDriver in example_test.go.

Selenium 4 standalone
svc, err := selenium.NewSeleniumServiceV4("selenium-server-4.x.jar", 4444)
// ...
wd, err := selenium.NewRemote(caps, "http://127.0.0.1:4444") // root URL, no /wd/hub

See Example_selenium4 in example_test.go.

Selenium 3 (legacy)

NewSeleniumService still targets Selenium 3 (GridLauncherV3) and listens under /wd/hub:

svc, err := selenium.NewSeleniumService("selenium-server.jar", 4444)
wd, err := selenium.NewRemote(caps, "http://127.0.0.1:4444/wd/hub")

See the original Example in example_test.go.

URL prefix cheat sheet
Backend Helper NewRemote urlPrefix
ChromeDriver 115+ NewChromeDriverService http://127.0.0.1:<port>
Geckodriver NewGeckoDriverService http://127.0.0.1:<port>
Selenium 4 NewSeleniumServiceV4 http://127.0.0.1:<port>
Selenium 3 NewSeleniumService http://127.0.0.1:<port>/wd/hub

Behavior notes (this fork)

Topic Behavior
HTTP client Default HTTPClient timeout is 120s (replace selenium.HTTPClient if needed)
Request headers JSON bodies send Content-Type: application/json
Cookies Optional fields use omitempty (zero Expiry/Path/… are omitted)
W3C find ByID / ByName / ByClassName map to CSS under W3C mode
W3C SendKeys Sends both text and value string list
Service debug Selenium 3 -debug only when SetDebug(true)
Linux teardown Process group + Pdeathsig to reduce orphan drivers
CDP ExecuteCDPCommand(cmd, params) via ChromeDriver goog/cdp/execute

Downloading Dependencies

Primarily for local tests / smoke:

$ cd vendor
$ go run init.go --alsologtostderr --download_browsers --download_latest
$ cd ..

Asset selection uses GOOS/GOARCH (linux64, mac-x64, mac-arm64, win32, win64). Chrome comes from Chrome for Testing Stable. Firefox on macOS/Windows may download installers/DMGs that need manual install.

Documentation

Smoke test (optional)

Needs Chrome + ChromeDriver. Without them the test skips (default CI stays green; runners that already have Chrome may execute it).

cd vendor && go run init.go --alsologtostderr --download_browsers && cd ..
go test -mod=mod -count=1 -timeout=5m -run TestSmokeChrome -v

Known Issues

Many failures come from the browser/driver, not this client. Please file an issue if the client misbehaves.

Selenium 2

No longer supported.

Selenium 3
  1. Selenium 3 NewSession does not implement the W3C-specified parameters.
Geckodriver (Standalone)
  1. Geckodriver does not support the Log API.
  2. Click issues.
  3. Control characters may need a terminating null key.
Chromedriver
  1. Headless Chrome does not support running extensions.
  2. Use the root service URL with ChromeDriver 115+ (not /wd/hub).

Changelog (summary)

Version Highlights
v0.10.0 Fork rehome, Go 1.22, GitHub Actions
v0.10.1 HTTP body close, client timeout, CurrentURL, cookie expiry
v0.10.2 W3C class/name find, NewSeleniumServiceV4
v0.10.3 Linux process-group / Pdeathsig orphan cleanup
v0.10.4 Multi-OS vendor/init.go, Chrome for Testing
v0.10.5 Content-Type, W3C SendKeys value list, cookie omitempty, gated -debug
v0.10.6 TestSmokeChrome; ChromeDriver tests without /wd/hub
v0.10.7 Smoke read-back via GetProperty on headless CI
v0.10.8 README modern usage; ExampleChromeDriver / Example_selenium4
v0.11.0 ExecuteCDPCommand; optional browser workflow
v0.11.1 Chinese README (README.zh-CN.md) + language switcher

Full notes: ChangeLog and Releases.

Optional browser CI

Manually run (or weekly schedule) the browser workflow: Actions → browser → Run workflow. It downloads Chrome for Testing and runs TestSmokeChrome (including CDP).

Optional next
  1. Feature PRs (Shadow DOM, Print, Select helpers, remote file upload)

Breaking Changes (historical)

22 August 2017

The Version constant was removed as it is unused.

18 April 2017

The Log method was changed to accept a typed constant for the type of log to retrieve, instead of a raw string. The return value was also changed to provide a more idiomatic type.

Hacking

Patches are welcome through GitHub pull requests. Please ensure that:

  1. A test is added for anything more than a trivial change and that the existing tests pass.
  2. gofmt has been run on the changed files. Optional pre-commit hook:
ln -s ../../misc/git/pre-commit .git/hooks/pre-commit

Issues

Testing Locally
sudo apt-get install xvfb openjdk-11-jre   # if needed
go test -mod=mod ./...

Top-level browser tests skip when binaries are missing:

  • TestChrome / TestSmokeChrome
  • TestFirefoxSelenium3 / TestFirefoxGeckoDriver
  • TestHTMLUnit (needs Java + JARs)

Configure paths with go test flags (see go test -args -help).

Testing With Docker
go test --docker

Or:

docker build -t go-selenium testing/
docker run --volume=$(pwd):/code --workdir=/code -it go-selenium bash
# inside: testing/docker-test.sh
Testing With Sauce Labs
go test --test.run=TestSauce --test.timeout=20m \
  --experimental_enable_sauce \
  --sauce_user_name=[username] \
  --sauce_access_key=[access key]

License

MIT — see LICENSE.

Documentation

Overview

Package selenium provides a client to drive web browser-based automation and testing.

See the example below for how to get started with this API.

This package can depend on several binaries being available, depending on which browsers will be used and how. To avoid needing to manage these dependencies, use a cloud-based browser testing environment, like Sauce Labs, BrowserStack or similar. Otherwise, use the methods provided by this API to specify the paths to the dependencies, which will have to be downloaded separately.

Example

This example shows how to navigate to a http://play.golang.org page, input a short program, run it, and inspect its output.

If you want to actually run this example:

  1. Ensure the file paths at the top of the function are correct.
  2. Remove the word "Example" from the comment at the bottom of the function.
  3. Run: go test -test.run=Example$ github.com/zninggo/selenium
package main

import (
	"fmt"
	"os"
	"strings"
	"time"

	"github.com/zninggo/selenium"
)

func main() {
	// Start a Selenium WebDriver server instance (if one is not already
	// running).
	const (
		// These paths will be different on your system.
		seleniumPath    = "vendor/selenium-server-standalone-3.4.jar"
		geckoDriverPath = "vendor/geckodriver-v0.18.0-linux64"
		port            = 8080
	)
	opts := []selenium.ServiceOption{
		selenium.StartFrameBuffer(),           // Start an X frame buffer for the browser to run in.
		selenium.GeckoDriver(geckoDriverPath), // Specify the path to GeckoDriver in order to use Firefox.
		selenium.Output(os.Stderr),            // Output debug information to STDERR.
	}
	selenium.SetDebug(true)
	service, err := selenium.NewSeleniumService(seleniumPath, port, opts...)
	if err != nil {
		panic(err) // panic is used only as an example and is not otherwise recommended.
	}
	defer service.Stop()

	// Connect to the WebDriver instance running locally.
	caps := selenium.Capabilities{"browserName": "firefox"}
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://localhost:%d/wd/hub", port))
	if err != nil {
		panic(err)
	}
	defer wd.Quit()

	// Navigate to the simple playground interface.
	if err := wd.Get("http://play.golang.org/?simple=1"); err != nil {
		panic(err)
	}

	// Get a reference to the text box containing code.
	elem, err := wd.FindElement(selenium.ByCSSSelector, "#code")
	if err != nil {
		panic(err)
	}
	// Remove the boilerplate code already in the text box.
	if err := elem.Clear(); err != nil {
		panic(err)
	}

	// Enter some new code in text box.
	err = elem.SendKeys(`
		package main
		import "fmt"

		func main() {
			fmt.Println("Hello WebDriver!")
		}
	`)
	if err != nil {
		panic(err)
	}

	// Click the run button.
	btn, err := wd.FindElement(selenium.ByCSSSelector, "#run")
	if err != nil {
		panic(err)
	}
	if err := btn.Click(); err != nil {
		panic(err)
	}

	// Wait for the program to finish running and get the output.
	outputDiv, err := wd.FindElement(selenium.ByCSSSelector, "#output")
	if err != nil {
		panic(err)
	}

	var output string
	for {
		output, err = outputDiv.Text()
		if err != nil {
			panic(err)
		}
		if output != "Waiting for remote server..." {
			break
		}
		time.Sleep(time.Millisecond * 100)
	}

	fmt.Printf("%s", strings.Replace(output, "\n\n", "\n", -1))
	// Example Output:
	// Hello WebDriver!
	//
	// Program exited.

	// The following shows an example of using the Actions API.
	// Please refer to the WC3 Actions spec for more detailed information.
	if err := wd.Get("http://play.golang.org/?simple=1"); err != nil {
		panic(err)
	}

	// Create a point which will be used as an offset to click on the
	// code editor text box element on the page.
	offset := selenium.Point{X: 100, Y: 100}

	// Call StorePointerActions to store a number of Pointer actions which
	// will be executed sequentially.
	// "mouse1" is used as a unique virtual device identifier for this
	// and future actions.
	// selenium.MousePointer is used to identify the type of the pointer.
	// The stored action chain will move the pointer and click on the code
	// editor text box on the page.
	wd.StorePointerActions("mouse1",
		selenium.MousePointer,
		// using selenium.FromViewport as the move origin
		// which calculates the offset from 0,0.
		// the other valid option is selenium.FromPointer.
		selenium.PointerMoveAction(0, offset, selenium.FromViewport),
		selenium.PointerPauseAction(250),
		selenium.PointerDownAction(selenium.LeftButton),
		selenium.PointerPauseAction(250),
		selenium.PointerUpAction(selenium.LeftButton),
	)

	// Call StoreKeyActions to store a number of Key actions which
	// will be executed sequentially.
	// "keyboard1" is used as a unique virtual device identifier
	// for this and future actions.
	// The stored action chain will send keyboard inputs to the browser.
	wd.StoreKeyActions("keyboard1",
		selenium.KeyDownAction(selenium.ControlKey),
		selenium.KeyPauseAction(50),
		selenium.KeyDownAction("a"),
		selenium.KeyPauseAction(50),
		selenium.KeyUpAction("a"),
		selenium.KeyUpAction(selenium.ControlKey),
		selenium.KeyDownAction("h"),
		selenium.KeyDownAction("e"),
		selenium.KeyDownAction("l"),
		selenium.KeyDownAction("l"),
		selenium.KeyDownAction("o"),
	)

	// Call PerformActions to execute stored action - based on
	// the order of the previous calls, PointerActions will be
	// executed first and then KeyActions.
	if err := wd.PerformActions(); err != nil {
		panic(err)
	}

	// Call ReleaseActions to release any PointerDown or
	// KeyDown Actions that haven't been released through an Action.
	if err := wd.ReleaseActions(); err != nil {
		panic(err)
	}

}
Example (Cdp)

Example_cdp shows ExecuteCDPCommand with ChromeDriver (Browser.getVersion).

package main

import (
	"fmt"

	"github.com/zninggo/selenium"
	"github.com/zninggo/selenium/chrome"
)

func main() {
	const (
		chromeDriverPath = "chromedriver"
		port             = 9515
	)
	svc, err := selenium.NewChromeDriverService(chromeDriverPath, port)
	if err != nil {
		panic(err)
	}
	defer svc.Stop()

	caps := selenium.Capabilities{"browserName": "chrome"}
	caps.AddChrome(chrome.Capabilities{
		Args: []string{"--headless=new", "--no-sandbox"},
		W3C:  true,
	})
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d", port))
	if err != nil {
		panic(err)
	}
	defer wd.Quit()

	res, err := wd.ExecuteCDPCommand("Browser.getVersion", nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%v\n", res)
}
Example (Selenium4)

Example_selenium4 shows how to start Selenium Server 4.x and connect without the legacy "/wd/hub" prefix.

To run this example you need a selenium-server-4.x.jar and Java installed.

package main

import (
	"fmt"

	"github.com/zninggo/selenium"
)

func main() {
	const (
		// Download from https://www.selenium.dev/downloads/ or via vendor/init.go
		// with --download_latest (writes selenium-server-4.jar when available).
		selenium4Path = "vendor/selenium-server-4.jar"
		port          = 4444
	)

	svc, err := selenium.NewSeleniumServiceV4(selenium4Path, port)
	if err != nil {
		panic(err)
	}
	defer svc.Stop()

	caps := selenium.Capabilities{"browserName": "chrome"}
	// Selenium 4 standalone listens at the root path.
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d", port))
	if err != nil {
		panic(err)
	}
	defer wd.Quit()

	if err := wd.Get("https://golang.org"); err != nil {
		panic(err)
	}
	title, err := wd.Title()
	if err != nil {
		panic(err)
	}
	fmt.Println(title)
}

Index

Examples

Constants

View Source
const (
	// DefaultWaitInterval is the default polling interval for selenium.Wait
	// function.
	DefaultWaitInterval = 100 * time.Millisecond

	// DefaultWaitTimeout is the default timeout for selenium.Wait function.
	DefaultWaitTimeout = 60 * time.Second
)
View Source
const (
	ByID              = "id"
	ByXPATH           = "xpath"
	ByLinkText        = "link text"
	ByPartialLinkText = "partial link text"
	ByName            = "name"
	ByTagName         = "tag name"
	ByClassName       = "class name"
	ByCSSSelector     = "css selector"
)

Methods by which to find elements.

View Source
const (
	NullKey       = string('\ue000')
	CancelKey     = string('\ue001')
	HelpKey       = string('\ue002')
	BackspaceKey  = string('\ue003')
	TabKey        = string('\ue004')
	ClearKey      = string('\ue005')
	ReturnKey     = string('\ue006')
	EnterKey      = string('\ue007')
	ShiftKey      = string('\ue008')
	ControlKey    = string('\ue009')
	AltKey        = string('\ue00a')
	PauseKey      = string('\ue00b')
	EscapeKey     = string('\ue00c')
	SpaceKey      = string('\ue00d')
	PageUpKey     = string('\ue00e')
	PageDownKey   = string('\ue00f')
	EndKey        = string('\ue010')
	HomeKey       = string('\ue011')
	LeftArrowKey  = string('\ue012')
	UpArrowKey    = string('\ue013')
	RightArrowKey = string('\ue014')
	DownArrowKey  = string('\ue015')
	InsertKey     = string('\ue016')
	DeleteKey     = string('\ue017')
	SemicolonKey  = string('\ue018')
	EqualsKey     = string('\ue019')
	Numpad0Key    = string('\ue01a')
	Numpad1Key    = string('\ue01b')
	Numpad2Key    = string('\ue01c')
	Numpad3Key    = string('\ue01d')
	Numpad4Key    = string('\ue01e')
	Numpad5Key    = string('\ue01f')
	Numpad6Key    = string('\ue020')
	Numpad7Key    = string('\ue021')
	Numpad8Key    = string('\ue022')
	Numpad9Key    = string('\ue023')
	MultiplyKey   = string('\ue024')
	AddKey        = string('\ue025')
	SeparatorKey  = string('\ue026')
	SubstractKey  = string('\ue027')
	DecimalKey    = string('\ue028')
	DivideKey     = string('\ue029')
	F1Key         = string('\ue031')
	F2Key         = string('\ue032')
	F3Key         = string('\ue033')
	F4Key         = string('\ue034')
	F5Key         = string('\ue035')
	F6Key         = string('\ue036')
	F7Key         = string('\ue037')
	F8Key         = string('\ue038')
	F9Key         = string('\ue039')
	F10Key        = string('\ue03a')
	F11Key        = string('\ue03b')
	F12Key        = string('\ue03c')
	MetaKey       = string('\ue03d')
)

Special keyboard keys, for SendKeys.

View Source
const (
	// Direct connection - no proxy in use.
	Direct ProxyType = "direct"
	// Manual proxy settings configured, e.g. setting a proxy for HTTP, a proxy
	// for FTP, etc.
	Manual = "manual"
	// Autodetect proxy, probably with WPAD
	Autodetect = "autodetect"
	// System settings used.
	System = "system"
	// PAC - Proxy autoconfiguration from a URL.
	PAC = "pac"
)
View Source
const (
	MousePointer PointerType = "mouse"
	PenPointer               = "pen"
	TouchPointer             = "touch"
)
View Source
const DefaultURLPrefix = "http://127.0.0.1:4444/wd/hub"

DefaultURLPrefix is the default HTTP endpoint that offers the WebDriver API.

Variables

View Source
var HTTPClient = &http.Client{
	Timeout: 120 * time.Second,
}

HTTPClient is the default client to use to communicate with the WebDriver server. It has a non-zero Timeout so hung remote ends do not block forever. Callers may replace it with a custom *http.Client.

Functions

func DeleteSession added in v0.10.0

func DeleteSession(urlPrefix, id string) error

DeleteSession deletes an existing session at the WebDriver instance specified by the urlPrefix and the session ID.

func SetDebug added in v0.8.4

func SetDebug(debug bool)

SetDebug sets debug mode

Types

type Actions added in v0.10.0

type Actions []map[string]interface{}

Actions stores KeyActions and PointerActions for later execution.

type Capabilities

type Capabilities map[string]interface{}

Capabilities configures both the WebDriver process and the target browsers, with standard and browser-specific options.

func (Capabilities) AddChrome added in v0.10.0

func (c Capabilities) AddChrome(f chrome.Capabilities)

AddChrome adds Chrome-specific capabilities.

func (Capabilities) AddFirefox added in v0.10.0

func (c Capabilities) AddFirefox(f firefox.Capabilities)

AddFirefox adds Firefox-specific capabilities.

func (Capabilities) AddLogging added in v0.10.0

func (c Capabilities) AddLogging(l log.Capabilities)

AddLogging adds logging configuration to the capabilities.

func (Capabilities) AddProxy added in v0.10.0

func (c Capabilities) AddProxy(p Proxy)

AddProxy adds proxy configuration to the capabilities.

func (Capabilities) SetLogLevel added in v0.10.0

func (c Capabilities) SetLogLevel(typ log.Type, level log.Level)

SetLogLevel sets the logging level of a component. It is a shortcut for passing a log.Capabilities instance to AddLogging.

type Condition added in v0.10.0

type Condition func(wd WebDriver) (bool, error)

Condition is an alias for a type that is passed as an argument for selenium.Wait(cond Condition) (error) function.

type Cookie struct {
	Name     string   `json:"name"`
	Value    string   `json:"value"`
	Path     string   `json:"path,omitempty"`
	Domain   string   `json:"domain,omitempty"`
	Secure   bool     `json:"secure,omitempty"`
	Expiry   uint     `json:"expiry,omitempty"`
	HTTPOnly bool     `json:"httpOnly,omitempty"`
	SameSite SameSite `json:"sameSite,omitempty"`
}

Cookie represents an HTTP cookie. Optional fields use omitempty so remote ends can apply their defaults instead of receiving zero values (tebeka/selenium#130, #282, PR #283).

type Error added in v0.10.0

type Error struct {
	// Err contains a general error string provided by the server.
	Err string `json:"error"`
	// Message is a detailed, human-readable message specific to the failure.
	Message string `json:"message"`
	// Stacktrace may contain the server-side stacktrace where the error occurred.
	Stacktrace string `json:"stacktrace"`
	// HTTPCode is the HTTP status code returned by the server.
	HTTPCode int
	// LegacyCode is the "Response Status Code" defined in the legacy Selenium
	// WebDriver JSON wire protocol. This code is only produced by older
	// Selenium WebDriver versions, Chromedriver, and InternetExplorerDriver.
	LegacyCode int
}

Error contains information about a failure of a command. See the table of these strings at https://www.w3.org/TR/webdriver/#handling-errors .

This error type is only returned by servers that implement the W3C specification.

func (*Error) Error added in v0.10.0

func (e *Error) Error() string

Error implements the error interface.

type FrameBuffer added in v0.10.0

type FrameBuffer struct {
	// Display is the X11 display number that the Xvfb process is hosting
	// (without the preceding colon).
	Display string
	// AuthPath is the path to the X11 authorization file that permits X clients
	// to use the X server. This is typically provided to the client via the
	// XAUTHORITY environment variable.
	AuthPath string
	// contains filtered or unexported fields
}

FrameBuffer controls an X virtual frame buffer running as a background process.

func NewFrameBuffer added in v0.10.0

func NewFrameBuffer() (*FrameBuffer, error)

NewFrameBuffer starts an X virtual frame buffer running in the background.

This is equivalent to calling NewFrameBufferWithOptions with an empty NewFrameBufferWithOptions.

func NewFrameBufferWithOptions added in v0.10.0

func NewFrameBufferWithOptions(options FrameBufferOptions) (*FrameBuffer, error)

NewFrameBufferWithOptions starts an X virtual frame buffer running in the background. FrameBufferOptions may be populated to change the behavior of the frame buffer.

func (FrameBuffer) Stop added in v0.10.0

func (f FrameBuffer) Stop() error

Stop kills the background frame buffer process and removes the X authorization file.

type FrameBufferOptions added in v0.10.0

type FrameBufferOptions struct {
	// ScreenSize is the option for the frame buffer screen size.
	// This is of the form "{width}x{height}[x{depth}]".  For example: "1024x768x24"
	ScreenSize string
}

FrameBufferOptions describes the options that can be used to create a frame buffer.

type KeyAction added in v0.10.0

type KeyAction map[string]interface{}

KeyAction represents an activity involving a keyboard key.

func KeyDownAction added in v0.10.0

func KeyDownAction(key string) KeyAction

KeyDownAction builds a KeyAction which presses and holds the specified key.

func KeyPauseAction added in v0.10.0

func KeyPauseAction(duration time.Duration) KeyAction

KeyPauseAction builds a KeyAction which pauses for the supplied duration.

func KeyUpAction added in v0.10.0

func KeyUpAction(key string) KeyAction

KeyUpAction builds a KeyAction press.

type MouseButton added in v0.10.0

type MouseButton int
const (
	LeftButton MouseButton = iota
	MiddleButton
	RightButton
)

Mouse buttons.

type Point

type Point struct {
	X, Y int
}

Point is a 2D point.

type PointerAction added in v0.10.0

type PointerAction map[string]interface{}

PointerAction represents an activity involving a pointer.

func PointerDownAction added in v0.10.0

func PointerDownAction(button MouseButton) PointerAction

PointerDown builds a PointerAction which presses and holds the specified pointer key.

func PointerMoveAction added in v0.10.0

func PointerMoveAction(duration time.Duration, offset Point, origin PointerMoveOrigin) PointerAction

PointerMove builds a PointerAction which moves the pointer.

func PointerPauseAction added in v0.10.0

func PointerPauseAction(duration time.Duration) PointerAction

PointerPause builds a PointerAction which pauses for the supplied duration.

func PointerUpAction added in v0.10.0

func PointerUpAction(button MouseButton) PointerAction

PointerUp builds an action which releases the specified pointer key.

type PointerMoveOrigin added in v0.10.0

type PointerMoveOrigin string

PointerMoveOrigin controls how the offset for the pointer move action is calculated.

const (
	// FromViewport calculates the offset from the viewport at 0,0.
	FromViewport PointerMoveOrigin = "viewport"
	// FromPointer calculates the offset from the current pointer position.
	FromPointer = "pointer"
)

type PointerType added in v0.10.0

type PointerType string

PointerType is the type of pointer used by StorePointerActions. There are 3 different types according to the WC3 implementation.

type Proxy added in v0.9.1

type Proxy struct {
	// Type is the type of proxy to use. This is required to be populated.
	Type ProxyType `json:"proxyType"`

	// AutoconfigURL is the URL to be used for proxy auto configuration. This is
	// required if Type is set to PAC.
	AutoconfigURL string `json:"proxyAutoconfigUrl,omitempty"`

	// The following are used when Type is set to Manual.
	//
	// Note that in Firefox, connections to localhost are not proxied by default,
	// even if a proxy is set. This can be overridden via a preference setting.
	FTP           string   `json:"ftpProxy,omitempty"`
	HTTP          string   `json:"httpProxy,omitempty"`
	SSL           string   `json:"sslProxy,omitempty"`
	SOCKS         string   `json:"socksProxy,omitempty"`
	SOCKSVersion  int      `json:"socksVersion,omitempty"`
	SOCKSUsername string   `json:"socksUsername,omitempty"`
	SOCKSPassword string   `json:"socksPassword,omitempty"`
	NoProxy       []string `json:"noProxy,omitempty"`

	// The W3C draft spec includes port fields as well. According to the
	// specification, ports can also be included in the above addresses. However,
	// in the Geckodriver implementation, the ports must be specified by these
	// additional fields.
	HTTPPort  int `json:"httpProxyPort,omitempty"`
	SSLPort   int `json:"sslProxyPort,omitempty"`
	SocksPort int `json:"socksProxyPort,omitempty"`
}

Proxy specifies configuration for proxies in the browser. Set the key "proxy" in Capabilities to an instance of this type.

type ProxyType added in v0.9.1

type ProxyType string

ProxyType is an enumeration of the types of proxies available.

type SameSite added in v0.10.0

type SameSite string

SameSite is the type for the SameSite field in Cookie.

const (
	SameSiteNone   SameSite = "None"
	SameSiteLax    SameSite = "Lax"
	SameSiteStrict SameSite = "Strict"
	SameSiteEmpty  SameSite = ""
)

type Service added in v0.10.0

type Service struct {
	// contains filtered or unexported fields
}

Service controls a locally-running Selenium subprocess.

func NewChromeDriverService added in v0.10.0

func NewChromeDriverService(path string, port int, opts ...ServiceOption) (*Service, error)

NewChromeDriverService starts a ChromeDriver instance in the background.

func NewGeckoDriverService added in v0.10.0

func NewGeckoDriverService(path string, port int, opts ...ServiceOption) (*Service, error)

NewGeckoDriverService starts a GeckoDriver instance in the background.

func NewSeleniumService added in v0.10.0

func NewSeleniumService(jarPath string, port int, opts ...ServiceOption) (*Service, error)

NewSeleniumService starts a Selenium 3 instance in the background. The service listens under /wd/hub (e.g. http://localhost:<port>/wd/hub). For Selenium 4+, use NewSeleniumServiceV4.

func NewSeleniumServiceV4 added in v0.10.2

func NewSeleniumServiceV4(jarPath string, port int, opts ...ServiceOption) (*Service, error)

NewSeleniumServiceV4 starts a Selenium 4+ standalone server in the background. jarPath should be a selenium-server-4.x (or newer) jar. The service listens at the root path (e.g. http://localhost:<port>), not /wd/hub. Pass that URL to NewRemote as the urlPrefix.

func (Service) FrameBuffer added in v0.10.0

func (s Service) FrameBuffer() *FrameBuffer

FrameBuffer returns the FrameBuffer if one was started by the service and nil otherwise.

func (*Service) Stop added in v0.10.0

func (s *Service) Stop() error

Stop shuts down the WebDriver service, and the X virtual frame buffer if one was started.

type ServiceOption added in v0.10.0

type ServiceOption func(*Service) error

ServiceOption configures a Service instance.

func ChromeDriver added in v0.10.0

func ChromeDriver(path string) ServiceOption

ChromeDriver sets the path for Chromedriver for the Selenium Server. This ServiceOption is only useful when calling NewSeleniumService or NewSeleniumServiceV4.

Example

ExampleChromeDriver shows the recommended setup for ChromeDriver 115+.

ChromeDriver serves the WebDriver endpoints at the server root — do not use the Selenium 3 "/wd/hub" suffix.

To run this example:

  1. Install chromedriver (or: cd vendor && go run init.go --download_browsers).
  2. Copy into a main package, or run via go test after providing Output.
  3. go test -mod=mod -run ExampleChromeDriver -v
package main

import (
	"fmt"

	"github.com/zninggo/selenium"
	"github.com/zninggo/selenium/chrome"
)

func main() {
	const (
		// Paths differ on each machine; "chromedriver" works if it is on PATH.
		chromeDriverPath = "chromedriver"
		port             = 9515
	)

	svc, err := selenium.NewChromeDriverService(chromeDriverPath, port)
	if err != nil {
		panic(err)
	}
	defer svc.Stop()

	caps := selenium.Capabilities{"browserName": "chrome"}
	caps.AddChrome(chrome.Capabilities{
		Args: []string{"--headless=new", "--no-sandbox", "--disable-dev-shm-usage"},
		W3C:  true,
	})

	// Root URL — not http://127.0.0.1:9515/wd/hub
	wd, err := selenium.NewRemote(caps, fmt.Sprintf("http://127.0.0.1:%d", port))
	if err != nil {
		panic(err)
	}
	defer wd.Quit()

	if err := wd.Get("https://golang.org"); err != nil {
		panic(err)
	}
	title, err := wd.Title()
	if err != nil {
		panic(err)
	}
	fmt.Println(title)
}

func Display added in v0.10.0

func Display(d, xauthPath string) ServiceOption

Display specifies the value to which set the DISPLAY environment variable, as well as the path to the Xauthority file containing credentials needed to write to that X server.

func GeckoDriver added in v0.10.0

func GeckoDriver(path string) ServiceOption

GeckoDriver sets the path to the geckodriver binary for the Selenium Server. Unlike other drivers, Selenium Server does not support specifying the geckodriver path at runtime. This ServiceOption is only useful when calling NewSeleniumService or NewSeleniumServiceV4.

func HTMLUnit added in v0.10.0

func HTMLUnit(path string) ServiceOption

HTMLUnit specifies the path to the JAR for the HTMLUnit driver (compiled with its dependencies).

https://github.com/SeleniumHQ/htmlunit-driver/releases

func JavaPath added in v0.10.0

func JavaPath(path string) ServiceOption

JavaPath specifies the path to the JRE.

func Output added in v0.10.0

func Output(w io.Writer) ServiceOption

Output specifies that the WebDriver service should log to the provided writer.

func StartFrameBuffer added in v0.10.0

func StartFrameBuffer() ServiceOption

StartFrameBuffer causes an X virtual frame buffer to start before the WebDriver service. The frame buffer process will be terminated when the service itself is stopped.

This is equivalent to calling StartFrameBufferWithOptions with an empty map.

func StartFrameBufferWithOptions added in v0.10.0

func StartFrameBufferWithOptions(options FrameBufferOptions) ServiceOption

StartFrameBufferWithOptions causes an X virtual frame buffer to start before the WebDriver service. The frame buffer process will be terminated when the service itself is stopped.

type Size

type Size struct {
	Width, Height int
}

Size is a size of HTML element.

type Status

type Status struct {
	// The following fields are used by Selenium and ChromeDriver.
	Java struct {
		Version string
	}
	Build struct {
		Version, Revision, Time string
	}
	OS struct {
		Arch, Name, Version string
	}

	// The following fields are specified by the W3C WebDriver specification and
	// are used by GeckoDriver.
	Ready   bool
	Message string
}

Status contains information returned by the Status method.

type WebDriver

type WebDriver interface {
	// Status returns various pieces of information about the server environment.
	Status() (*Status, error)

	// NewSession starts a new session and returns the session ID.
	NewSession() (string, error)

	// SessionId returns the current session ID
	//
	// Deprecated: This identifier is not Go-style correct. Use SessionID
	// instead.
	SessionId() string

	// SessionID returns the current session ID.
	SessionID() string

	// SwitchSession switches to the given session ID.
	SwitchSession(sessionID string) error

	// Capabilities returns the current session's capabilities.
	Capabilities() (Capabilities, error)

	// SetAsyncScriptTimeout sets the amount of time that asynchronous scripts
	// are permitted to run before they are aborted. The timeout will be rounded
	// to nearest millisecond.
	SetAsyncScriptTimeout(timeout time.Duration) error
	// SetImplicitWaitTimeout sets the amount of time the driver should wait when
	// searching for elements. The timeout will be rounded to nearest millisecond.
	SetImplicitWaitTimeout(timeout time.Duration) error
	// SetPageLoadTimeout sets the amount of time the driver should wait when
	// loading a page. The timeout will be rounded to nearest millisecond.
	SetPageLoadTimeout(timeout time.Duration) error

	// Quit ends the current session. The browser instance will be closed.
	Quit() error

	// CurrentWindowHandle returns the ID of current window handle.
	CurrentWindowHandle() (string, error)
	// WindowHandles returns the IDs of current open windows.
	WindowHandles() ([]string, error)
	// CurrentURL returns the browser's current URL.
	CurrentURL() (string, error)
	// Title returns the current page's title.
	Title() (string, error)
	// PageSource returns the current page's source.
	PageSource() (string, error)
	// Close closes the current window.
	Close() error
	// SwitchFrame switches to the given frame. The frame parameter can be the
	// frame's ID as a string, its WebElement instance as returned by
	// GetElement, or nil to switch to the current top-level browsing context.
	SwitchFrame(frame interface{}) error
	// SwitchWindow switches the context to the specified window.
	SwitchWindow(name string) error
	// CloseWindow closes the specified window.
	CloseWindow(name string) error
	// MaximizeWindow maximizes a window. If the name is empty, the current
	// window will be maximized.
	MaximizeWindow(name string) error
	// ResizeWindow changes the dimensions of a window. If the name is empty, the
	// current window will be maximized.
	ResizeWindow(name string, width, height int) error

	// Get navigates the browser to the provided URL.
	Get(url string) error
	// Forward moves forward in history.
	Forward() error
	// Back moves backward in history.
	Back() error
	// Refresh refreshes the page.
	Refresh() error

	// FindElement finds exactly one element in the current page's DOM.
	FindElement(by, value string) (WebElement, error)
	// FindElement finds potentially many elements in the current page's DOM.
	FindElements(by, value string) ([]WebElement, error)
	// ActiveElement returns the currently active element on the page.
	ActiveElement() (WebElement, error)

	// DecodeElement decodes a single element response.
	DecodeElement([]byte) (WebElement, error)
	// DecodeElements decodes a multi-element response.
	DecodeElements([]byte) ([]WebElement, error)

	// GetCookies returns all of the cookies in the browser's jar.
	GetCookies() ([]Cookie, error)
	// GetCookie returns the named cookie in the jar, if present. This method is
	// only implemented for Firefox.
	GetCookie(name string) (Cookie, error)
	// AddCookie adds a cookie to the browser's jar.
	AddCookie(cookie *Cookie) error
	// DeleteAllCookies deletes all of the cookies in the browser's jar.
	DeleteAllCookies() error
	// DeleteCookie deletes a cookie to the browser's jar.
	DeleteCookie(name string) error

	// Click clicks a mouse button. The button should be one of RightButton,
	// MiddleButton or LeftButton.
	Click(button int) error
	// DoubleClick clicks the left mouse button twice.
	DoubleClick() error
	// ButtonDown causes the left mouse button to be held down.
	ButtonDown() error
	// ButtonUp causes the left mouse button to be released.
	ButtonUp() error

	// StoreKeyActions store provided actions until they are executed
	// by PerformActions or released by ReleaseActions.
	// inputID is a string used as a unique virtual device identifier for this
	// and future actions, the value can be set to any valid string
	// and used to refer to this specific device in future calls.
	StoreKeyActions(inputID string, actions ...KeyAction)

	// StorePointerActions store provided actions until they are executed
	// by PerformActions or released by ReleaseActions.
	// inputID is a string used as a unique virtual device identifier for this
	// and future actions, the value can be set to any valid string
	// and used to refer to this specific device in future calls.
	StorePointerActions(inputID string, pointer PointerType, actions ...PointerAction)

	// PerformActions executes actions previously stored by calls to StorePointerActions and StoreKeyActions.
	PerformActions() error
	// ReleaseActions releases keys and pointer buttons if they are pressed,
	// triggering any events as if they were performed by a regular action.
	ReleaseActions() error

	// SendModifier sends the modifier key to the active element. The modifier
	// can be one of ShiftKey, ControlKey, AltKey, MetaKey.
	//
	// Deprecated: Use KeyDown or KeyUp instead.
	SendModifier(modifier string, isDown bool) error
	// KeyDown sends a sequence of keystrokes to the active element. This method
	// is similar to SendKeys but without the implicit termination. Modifiers are
	// not released at the end of each call.
	KeyDown(keys string) error
	// KeyUp indicates that a previous keystroke sent by KeyDown should be
	// released.
	KeyUp(keys string) error
	// Screenshot takes a screenshot of the browser window.
	Screenshot() ([]byte, error)
	// Log fetches the logs. Log types must be previously configured in the
	// capabilities.
	//
	// NOTE: will return an error (not implemented) on IE11 or Edge drivers.
	Log(typ log.Type) ([]log.Message, error)

	// DismissAlert dismisses current alert.
	DismissAlert() error
	// AcceptAlert accepts the current alert.
	AcceptAlert() error
	// AlertText returns the current alert text.
	AlertText() (string, error)
	// SetAlertText sets the current alert text.
	SetAlertText(text string) error

	// ExecuteScript executes a script.
	ExecuteScript(script string, args []interface{}) (interface{}, error)
	// ExecuteScriptAsync asynchronously executes a script.
	ExecuteScriptAsync(script string, args []interface{}) (interface{}, error)

	// ExecuteScriptRaw executes a script but does not perform JSON decoding.
	ExecuteScriptRaw(script string, args []interface{}) ([]byte, error)
	// ExecuteScriptAsyncRaw asynchronously executes a script but does not
	// perform JSON decoding.
	ExecuteScriptAsyncRaw(script string, args []interface{}) ([]byte, error)

	// ExecuteCDPCommand runs a Chrome DevTools Protocol command via ChromeDriver
	// (POST /session/{id}/goog/cdp/execute). cmd is a CDP method name such as
	// "Browser.getVersion"; params may be nil or a map/struct JSON-encoded as
	// the CDP params object. The decoded "value" field is returned.
	// Only supported with Chrome/Chromium driven by ChromeDriver.
	ExecuteCDPCommand(cmd string, params interface{}) (interface{}, error)

	// WaitWithTimeoutAndInterval waits for the condition to evaluate to true.
	WaitWithTimeoutAndInterval(condition Condition, timeout, interval time.Duration) error

	// WaitWithTimeout works like WaitWithTimeoutAndInterval, but with default polling interval.
	WaitWithTimeout(condition Condition, timeout time.Duration) error

	//Wait works like WaitWithTimeoutAndInterval, but using the default timeout and polling interval.
	Wait(condition Condition) error
}

WebDriver defines methods supported by WebDriver drivers.

func NewRemote

func NewRemote(capabilities Capabilities, urlPrefix string) (WebDriver, error)

NewRemote creates new remote client, this will also start a new session. capabilities provides the desired capabilities. urlPrefix is the URL to the Selenium server, must be prefixed with protocol (http, https, ...).

Providing an empty string for urlPrefix causes the DefaultURLPrefix to be used.

type WebElement

type WebElement interface {
	// Click clicks on the element.
	Click() error
	// SendKeys types into the element.
	SendKeys(keys string) error
	// Submit submits the button.
	Submit() error
	// Clear clears the element.
	Clear() error
	// MoveTo moves the mouse to relative coordinates from center of element, If
	// the element is not visible, it will be scrolled into view.
	MoveTo(xOffset, yOffset int) error

	// FindElement finds a child element.
	FindElement(by, value string) (WebElement, error)
	// FindElement finds multiple children elements.
	FindElements(by, value string) ([]WebElement, error)

	// TagName returns the element's name.
	TagName() (string, error)
	// Text returns the text of the element.
	Text() (string, error)
	// IsSelected returns true if element is selected.
	IsSelected() (bool, error)
	// IsEnabled returns true if the element is enabled.
	IsEnabled() (bool, error)
	// IsDisplayed returns true if the element is displayed.
	IsDisplayed() (bool, error)
	// GetAttribute returns the named HTML attribute of the element.
	GetAttribute(name string) (string, error)
	// GetProperty returns the DOM property of the element. The DOM property
	// values can change (e.g. input value), the HTML attributes can't.
	GetProperty(name string) (string, error)
	// Location returns the element's location.
	Location() (*Point, error)
	// LocationInView returns the element's location once it has been scrolled
	// into view.
	LocationInView() (*Point, error)
	// Size returns the element's size.
	Size() (*Size, error)
	// CSSProperty returns the value of the specified CSS property of the
	// element.
	CSSProperty(name string) (string, error)
	// Screenshot takes a screenshot of the attribute scroll'ing if necessary.
	Screenshot(scroll bool) ([]byte, error)
}

WebElement defines method supported by web elements.

Directories

Path Synopsis
Package chrome provides Chrome-specific options for WebDriver.
Package chrome provides Chrome-specific options for WebDriver.
Package firefox provides Firefox-specific types for WebDriver.
Package firefox provides Firefox-specific types for WebDriver.
internal
seleniumtest
Package seleniumtest provides tests to exercise package selenium.
Package seleniumtest provides tests to exercise package selenium.
zip
Package zip creates Zip files.
Package zip creates Zip files.
Package log provides logging-related configuration types and constants.
Package log provides logging-related configuration types and constants.
Package sauce interacts with the Sauce Labs hosted browser testing environment.
Package sauce interacts with the Sauce Labs hosted browser testing environment.
Binary init downloads the necessary files to perform an integration test between this WebDriver client and multiple versions of Selenium and browsers.
Binary init downloads the necessary files to perform an integration test between this WebDriver client and multiple versions of Selenium and browsers.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL