selenium: Index | Examples | Files | Directories

package selenium

import ""

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.

This example shows how to navigate to a 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
3. Run:
   go test$


// 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.
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 {
defer wd.Quit()

// Navigate to the simple playground interface.
if err := wd.Get(""); err != nil {

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

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

		func main() {
			fmt.Println("Hello WebDriver!\n")
if err != nil {

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

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

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

fmt.Printf("%s", strings.Replace(output, "\n\n", "\n", -1))

// Example Output:
// Hello WebDriver!
// Program exited.



Package Files

common.go doc.go remote.go selenium.go service.go


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
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.

const (
    LeftButton = iota

Mouse buttons.

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.

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"
const DefaultURLPrefix = ""

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


var HTTPClient = http.DefaultClient

HTTPClient is the default client to use to communicate with the WebDriver server.

func DeleteSession Uses

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 Uses

func SetDebug(debug bool)

SetDebug sets debug mode

type Capabilities Uses

type Capabilities map[string]interface{}

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

func (Capabilities) AddChrome Uses

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

AddChrome adds Chrome-specific capabilities.

func (Capabilities) AddFirefox Uses

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

AddFirefox adds Firefox-specific capabilities.

func (Capabilities) AddLogging Uses

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

AddLogging adds logging configuration to the capabilities.

func (Capabilities) AddProxy Uses

func (c Capabilities) AddProxy(p Proxy)

AddProxy adds proxy configuration to the capabilities.

func (Capabilities) SetLogLevel Uses

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 Uses

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"`
    Domain   string `json:"domain"`
    Secure   bool   `json:"secure"`
    Expiry   uint   `json:"expiry"`
    HTTPOnly bool   `json:"httpOnly"`

Cookie represents an HTTP cookie.

type Error Uses

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 .

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

func (*Error) Error Uses

func (e *Error) Error() string

Error implements the error interface.

type FrameBuffer Uses

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 Uses

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 Uses

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 Uses

func (f FrameBuffer) Stop() error

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

type FrameBufferOptions Uses

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 Point Uses

type Point struct {
    X, Y int

Point is a 2D point.

type Proxy Uses

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 Uses

type ProxyType string

ProxyType is an enumeration of the types of proxies available.

type Service Uses

type Service struct {
    // contains filtered or unexported fields

Service controls a locally-running Selenium subprocess.

func NewChromeDriverService Uses

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

NewChromeDriverService starts a ChromeDriver instance in the background.

func NewGeckoDriverService Uses

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

NewGeckoDriverService starts a GeckoDriver instance in the background.

func NewSeleniumService Uses

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

NewSeleniumService starts a Selenium instance in the background.

func (Service) FrameBuffer Uses

func (s Service) FrameBuffer() *FrameBuffer

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

func (*Service) Stop Uses

func (s *Service) Stop() error

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

type ServiceOption Uses

type ServiceOption func(*Service) error

ServiceOption configures a Service instance.

func ChromeDriver Uses

func ChromeDriver(path string) ServiceOption

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

func Display Uses

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 Uses

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.

func HTMLUnit Uses

func HTMLUnit(path string) ServiceOption

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

func JavaPath Uses

func JavaPath(path string) ServiceOption

JavaPath specifies the path to the JRE.

func Output Uses

func Output(w io.Writer) ServiceOption

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

func StartFrameBuffer Uses

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 Uses

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 Uses

type Size struct {
    Width, Height int

Size is a size of HTML element.

type Status Uses

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 Uses

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

    // 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)

    // 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 Uses

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 Uses

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 attribute of the element.
    GetAttribute(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.


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

Package selenium imports 23 packages (graph) and is imported by 41 packages. Updated 2020-05-01. Refresh now. Tools for package owners.