selenium

package module
v0.0.0-...-6f7f74f Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2024 License: MIT Imports: 23 Imported by: 0

README

The most complete, best-tested WebDriver client for Go

GoDoc Travis Go Report Card

About

This is a WebDriver client for Go. It supports the WebDriver protocol and has been tested with various versions of Selenium WebDriver, Firefox and Geckodriver, and Chrome and ChromeDriver,

selenium is currently maintained by Eric Garrido (@minusnine).

Installing

Run

go get -t -d github.com/tebeka/selenium

to fetch the package.

The package requires a working WebDriver installation, which can include recent versions of a web browser being driven by Selenium WebDriver.

Downloading Dependencies

We provide a means to download the ChromeDriver binary, the Firefox binary, the Selenium WebDriver JARs, and the Sauce Connect proxy binary. This is primarily intended for testing.

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

Re-run this periodically to get up-to-date versions of these binaries.

Documentation

The API documentation is at https://godoc.org/github.com/tebeka/selenium. See the example and unit tests(for sauce, selenium and service) for better usage information.

Known Issues

Any issues are usually because the underlying browser automation framework has a bug or inconsistency. Where possible, we try to cover up these underlying problems in the client, but sometimes workarounds require higher-level intervention.

Please feel free to file an issue if this client doesn't work as expected.

Below are known issues that affect the usage of this API. There are likely others filed on the respective issue trackers.

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 because it hasn't been defined in the spec yet.
  2. Firefox via Geckodriver (and also through Selenium) doesn't handle clicking on an element.
  3. Firefox via Geckodriver doesn't handle sending control characters without appending a terminating null key.
Chromedriver
  1. Headless Chrome does not support running extensions.

Breaking Changes

There are a number of upcoming changes that break backward compatibility in an effort to improve and adapt the existing API. They are listed here:

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 encouraged 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. See below for instructions on setting up your test environment.

  2. Please ensure that gofmt has been run on the changed files before committing. Install a pre-commit hook with the following command:

    $ ln -s ../../misc/git/pre-commit .git/hooks/pre-commit

See the issue tracker for features that need implementing.

Testing Locally

Install xvfb and Java if they is not already installed, e.g.:

sudo apt-get install xvfb openjdk-11-jre

Run the tests:

$ go test
  • There is one top-level test for each of:

    1. Chromium and ChromeDriver.
    2. A new version of Firefox and Selenium 3.
    3. HTMLUnit, a Java-based lightweight headless browser implementation.
    4. A new version of Firefox directly against Geckodriver.

    There are subtests that are shared between both top-level tests.

  • To run only one of the top-level tests, pass one of:

    • -test.run=TestFirefoxSelenium3,
    • -test.run=TestFirefoxGeckoDriver,
    • -test.run=TestHTMLUnit, or
    • -test.run=TestChrome.

    To run a specific subtest, pass -test.run=Test<Browser>/<subtest> as appropriate. This flag supports regular expressions.

  • If the Chrome or Firefox binaries, the Selenium JAR, the Geckodriver binary, or the ChromeDriver binary cannot be found, the corresponding tests will be skipped.

  • The binaries and JAR under test can be configured by passing flags to go test. See the available flags with go test --arg --help.

  • Add the argument -test.v to see detailed output from the test automation framework.

Testing With Docker

To ensure hermeticity, we also have tests that run under Docker. You will need an installed and running Docker system.

To run the tests under Docker, run:

$ go test --docker

This will create a new Docker container and run the tests in it. (Note: flags supplied to this invocation are not curried through to the go test invocation within the Docker container).

For debugging Docker directly, run the following commands:

$ docker build -t go-selenium testing/
$ docker run --volume=$(pwd):/code --workdir=/code -it go-selenium bash
root@6c7951e41db6:/code# testing/docker-test.sh
... lots of testing output ...
Testing With Sauce Labs

Tests can be run using a browser located in the cloud via Sauce Labs.

To run the tests under Sauce, run:

$ go test --test.run=TestSauce --test.timeout=20m \
  --experimental_enable_sauce \
  --sauce_user_name=[username goes here] \
  --sauce_access_key=[access key goes here]

The Sauce access key can be obtained via the Sauce Labs user settings page.

Test results can be viewed through the Sauce Labs Dashboard.

License

This project is licensed under the MIT 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/vertexcover-io/selenium
package main

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

	"github.com/vertexcover-io/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.
	selenium.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.
	selenium.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)
	}

}
Output:

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

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

Functions

func DeleteSession

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

func SetDebug(debug bool)

SetDebug sets debug mode

Types

type Actions

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

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

AddChrome adds Chrome-specific capabilities.

func (Capabilities) AddFirefox

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

AddFirefox adds Firefox-specific capabilities.

func (Capabilities) AddLogging

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

AddLogging adds logging configuration to the capabilities.

func (Capabilities) AddProxy

func (c Capabilities) AddProxy(p Proxy)

AddProxy adds proxy configuration to the capabilities.

func (Capabilities) SetLogLevel

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

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"`
	SameSite SameSite `json:"sameSite,omitempty"`
}

Cookie represents an HTTP cookie.

type Error

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

func (e *Error) Error() string

Error implements the error interface.

type FrameBuffer

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

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

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

func (f FrameBuffer) Stop() error

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

type FrameBufferOptions

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

type KeyAction map[string]interface{}

KeyAction represents an activity involving a keyboard key.

func KeyDownAction

func KeyDownAction(key string) KeyAction

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

func KeyPauseAction

func KeyPauseAction(duration time.Duration) KeyAction

KeyPauseAction builds a KeyAction which pauses for the supplied duration.

func KeyUpAction

func KeyUpAction(key string) KeyAction

KeyUpAction builds a KeyAction press.

type MouseButton

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

type PointerAction map[string]interface{}

PointerAction represents an activity involving a pointer.

func PointerDownAction

func PointerDownAction(button MouseButton) PointerAction

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

func PointerMoveAction

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

PointerMove builds a PointerAction which moves the pointer.

func PointerPauseAction

func PointerPauseAction(duration time.Duration) PointerAction

PointerPause builds a PointerAction which pauses for the supplied duration.

func PointerUpAction

func PointerUpAction(button MouseButton) PointerAction

PointerUp builds an action which releases the specified pointer key.

type PointerMoveOrigin

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

type PointerType string

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

type Proxy

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

type ProxyType string

ProxyType is an enumeration of the types of proxies available.

type SameSite

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

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

Service controls a locally-running Selenium subprocess.

func NewChromeDriverService

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

NewChromeDriverService starts a ChromeDriver instance in the background.

func NewGeckoDriverService

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

NewGeckoDriverService starts a GeckoDriver instance in the background.

func NewSeleniumService

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

NewSeleniumService starts a Selenium instance in the background.

func (Service) FrameBuffer

func (s Service) FrameBuffer() *FrameBuffer

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

func (*Service) Stop

func (s *Service) Stop() error

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

type ServiceOption

type ServiceOption func(*Service) error

ServiceOption configures a Service instance.

func ChromeDriver

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

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

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

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

func JavaPath(path string) ServiceOption

JavaPath specifies the path to the JRE.

func Output

func Output(w io.Writer) ServiceOption

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

func StartFrameBuffer

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

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)

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

func ConnectRemote(urlPrefix string, sessionID string) (WebDriver, error)

ConnectRemote connectes with existing remote client. 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.

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