webdriver

package module
Version: v0.0.0-...-ee7e4d5 Latest Latest
Warning

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

Go to latest
Published: May 22, 2021 License: BSD-2-Clause Imports: 17 Imported by: 0

README

This project is not maintained and it is effectively abandoned, if you have interest in this code you should probably clone it.

webdriver

The package implements a WebDriver that communicate with a browser using the JSON Wire Protocol (See https://code.google.com/p/selenium/wiki/JsonWireProtocol). This is a pure go library and doesn't require a running Selenium driver. It currently supports Firefox (using the WebDriver extension) and Chrome (using the standalone server chromedriver). It should be fairly easy to add other browser that directly implement the wire protocol.

Version: 0.1
Tests are partial and have been run only on Linux (with firefox webdriver 2.32.0 and chromedriver 2.1).

Install:
$ go get github.com/fedesog/webdriver

Requires:

Example:

chromeDriver := webdriver.NewChromeDriver("/path/to/chromedriver")
err := chromeDriver.Start()
if err != nil {
	log.Println(err)
}
desired := webdriver.Capabilities{"Platform": "Linux"}
required := webdriver.Capabilities{}
session, err := chromeDriver.NewSession(desired, required)
if err != nil {
	log.Println(err)
}
err = session.Url("http://golang.org")
if err != nil {
	log.Println(err)
}
time.Sleep(10 * time.Second)
session.Delete()
chromeDriver.Stop()

Documentation

Overview

The package implementation a WebDriver that communicate with a browser using the JSON Wire Protocol.

See https://code.google.com/p/selenium/wiki/JsonWireProtocol

Example:

chromeDriver := webdriver.NewChromeDriver("/path/to/chromedriver")
err := chromeDriver.Start()
if err != nil {
	log.Println(err)
}
desired := webdriver.Capabilities{"Platform": "Linux"}
required := webdriver.Capabilities{}
session, err := chromeDriver.NewSession(desired, required)
if err != nil {
	log.Println(err)
}
err = session.Url("http://golang.org")
if err != nil {
	log.Println(err)
}
time.Sleep(60 * time.Second)
session.Delete()
chromeDriver.Stop()

Index

Constants

View Source
const (
	Success                    = 0
	NoSuchDriver               = 6
	NoSuchElement              = 7
	NoSuchFrame                = 8
	UnknownCommand             = 9
	StaleElementReference      = 10
	ElementNotVisible          = 11
	InvalidElementState        = 12
	UnknownError               = 13
	ElementIsNotSelectable     = 15
	JavaScriptError            = 17
	XPathLookupError           = 19
	Timeout                    = 21
	NoSuchWindow               = 23
	InvalidCookieDomain        = 24
	UnableToSetCookie          = 25
	UnexpectedAlertOpen        = 26
	NoAlertOpenError           = 27
	ScriptTimeout              = 28
	InvalidElementCoordinates  = 29
	IMENotAvailable            = 30
	IMEEngineActivationFailed  = 31
	InvalidSelector            = 32
	SessionNotCreatedException = 33
	MoveTargetOutOfBounds      = 34
)
View Source
const (
	//Returns an element whose class name contains the search value; compound class names are not permitted.
	ClassName = FindElementStrategy("class name")
	//Returns an element matching a CSS selector.
	CSS_Selector = FindElementStrategy("css selector")
	//Returns an element whose ID attribute matches the search value.
	ID = FindElementStrategy("id")
	//Returns an element whose NAME attribute matches the search value.
	Name = FindElementStrategy("name")
	//Returns an anchor element whose visible text matches the search value.
	LinkText = FindElementStrategy("link text")
	//Returns an anchor element whose visible text partially matches the search value.
	PartialLinkText = FindElementStrategy("partial link text")
	//Returns an element whose tag name matches the search value.
	TagName = FindElementStrategy("tag name")
	//Returns an element matching an XPath expression.
	XPath = FindElementStrategy("xpath")
)
View Source
const (
	LogAll     = LogLevel("ALL")
	LogDebug   = LogLevel("DEBUG")
	LogInfo    = LogLevel("INFO")
	LogWarning = LogLevel("WARNING")
	LogSevere  = LogLevel("SEVERE")
	LogOff     = LogLevel("OFF")
)
View Source
const (
	CacheStatusUncached    = HTML5CacheStatus(0)
	CacheStatusIdle        = HTML5CacheStatus(1)
	CacheStatusChecking    = HTML5CacheStatus(2)
	CacheStatusDownloading = HTML5CacheStatus(3)
	CacheStatusUpdateReady = HTML5CacheStatus(4)
	CacheStatusObsolete    = HTML5CacheStatus(5)
)
View Source
const (
	//TODO what is actually returned?
	LANDSCAPE = iota
	PORTRAIT
)
View Source
const (
	LeftButton   = MouseButton(0)
	MiddleButton = MouseButton(1)
	RightButton  = MouseButton(2)
)

Variables

This section is empty.

Functions

func GetDefaultPrefs

func GetDefaultPrefs() map[string]interface{}

Populate a map with default firefox preferences

Types

type Build

type Build struct {
	Version  string
	Revision string
	Time     string
}

Server built details.

type Capabilities

type Capabilities map[string]interface{}

Capabilities is a map that stores capabilities of a session.

type ChromeDriver

type ChromeDriver struct {
	WebDriverCore
	//The port that ChromeDriver listens on. Default: 9515
	Port int
	//The URL path prefix to use for all incoming WebDriver REST requests. Default: ""
	BaseUrl string
	//The number of threads to use for handling HTTP requests. Default: 4
	Threads int
	//The path to use for the ChromeDriver server log. Default: ./chromedriver.log
	LogPath string
	// Log file to dump chromedriver stdout/stderr. If "" send to terminal. Default: ""
	LogFile string
	// Start method fails if Chromedriver doesn't start in less than StartTimeout. Default 20s.
	StartTimeout time.Duration
	// contains filtered or unexported fields
}

func NewChromeDriver

func NewChromeDriver(path string) *ChromeDriver

create a new service using chromedriver. function returns an error if not supported switches are passed. Actual content of valid-named switches is not validate and is passed as it is. switch silent is removed (output is needed to check if chromedriver started correctly)

func (*ChromeDriver) NewSession

func (d *ChromeDriver) NewSession(desired, required Capabilities) (*Session, error)

func (*ChromeDriver) Sessions

func (d *ChromeDriver) Sessions() ([]Session, error)

func (*ChromeDriver) Start

func (d *ChromeDriver) Start() error

func (*ChromeDriver) Stop

func (d *ChromeDriver) Stop() error

type ChromeSwitches

type ChromeSwitches map[string]interface{}

type CommandError

type CommandError struct {
	StatusCode int
	ErrorType  string
	Message    string
	Screen     string
	Class      string
	StackTrace []StackFrame
}

func (CommandError) Error

func (e CommandError) Error() string
type Cookie struct {
	Name   string
	Value  string
	Path   string
	Domain string
	Secure bool
	Expiry int
}

type FindElementStrategy

type FindElementStrategy string

type FirefoxDriver

type FirefoxDriver struct {
	WebDriverCore
	// The port firefox webdriver listens on. This port - 1 will be used as a mutex to avoid starting multiple firefox instances listening to the same port. Default: 7055
	Port int
	// Start method fails if lock (see Port) is not acquired before LockPortTimeout. Default 60s
	LockPortTimeout time.Duration
	// Start method fails if Firefox doesn't start in less than StartTimeout. Default 20s.
	StartTimeout time.Duration
	// Log file to dump firefox stdout/stderr. If "" send to terminal. Default: ""
	LogFile string
	// Firefox preferences. Default: see method GetDefaultPrefs
	Prefs map[string]interface{}
	// If temporary profile has to be deleted when closing. Default: true
	DeleteProfileOnClose bool
	// contains filtered or unexported fields
}

func NewFirefoxDriver

func NewFirefoxDriver(firefoxPath string, xpiPath string) *FirefoxDriver

func (*FirefoxDriver) NewSession

func (d *FirefoxDriver) NewSession(desired, required Capabilities) (*Session, error)

func (*FirefoxDriver) Sessions

func (d *FirefoxDriver) Sessions() ([]Session, error)

func (*FirefoxDriver) SetLogPath

func (d *FirefoxDriver) SetLogPath(path string)

Equivalent to setting the following firefox preferences to: "webdriver.log.file": path/jsconsole.log "webdriver.log.driver.file": path/driver.log "webdriver.log.profiler.file": path/profiler.log "webdriver.log.browser.file": path/browser.log

func (*FirefoxDriver) Start

func (d *FirefoxDriver) Start() error

func (*FirefoxDriver) Stop

func (d *FirefoxDriver) Stop() error

type GeoLocation

type GeoLocation struct {
	Latitude  float64 `json:"latitude"`
	Longitude float64 `json:"longitude"`
	Altitude  float64 `json:"altitude"`
}

type HTML5CacheStatus

type HTML5CacheStatus int

type InstallRDF

type InstallRDF struct {
	Description InstallRDFDescription
}

type InstallRDFDescription

type InstallRDFDescription struct {
	Id string `xml:"id"`
}

type LogEntry

type LogEntry struct {
	TimeStamp int //TODO timestamp number type?
	Level     string
	Message   string
}

type LogLevel

type LogLevel string

type MouseButton

type MouseButton int

type OS

type OS struct {
	Arch    string
	Name    string
	Version string
}

Server OS details

type Position

type Position struct {
	X int
	Y int
}

type ScreenOrientation

type ScreenOrientation string

type Session

type Session struct {
	Id           string
	Capabilities Capabilities
	// contains filtered or unexported fields
}

A session.

func (Session) AcceptAlert

func (s Session) AcceptAlert() error

Accepts the currently displayed alert dialog.

func (Session) Back

func (s Session) Back() error

Navigate backwards in the browser history, if possible.

func (Session) ButtonDown

func (s Session) ButtonDown(button MouseButton) error

Click and hold the left mouse button (at the coordinates set by the last moveto command).

func (Session) ButtonUp

func (s Session) ButtonUp(button MouseButton) error

Releases the mouse button previously held (where the mouse is currently at).

func (Session) Click

func (s Session) Click(button MouseButton) error

Click any mouse button (at the coordinates set by the last moveto command).

Note that calling this command after calling buttondown and before calling button up (or any out-of-order interactions sequence) will yield undefined behaviour).

func (Session) CloseCurrentWindow

func (s Session) CloseCurrentWindow() error

Close the current window.

func (Session) Delete

func (s Session) Delete() error

Delete the session.

func (Session) DeleteCookieByName

func (s Session) DeleteCookieByName(name string) error

Delete the cookie with the given name.

func (Session) DeleteCookies

func (s Session) DeleteCookies() error

Delete all cookies visible to the current page.

func (Session) DismissAlert

func (s Session) DismissAlert() error

Dismisses the currently displayed alert dialog.

func (Session) DoubleClick

func (s Session) DoubleClick() error

Double-clicks at the current mouse coordinates (set by moveto).

func (Session) ExecuteScript

func (s Session) ExecuteScript(script string, args []interface{}) ([]byte, error)

Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client. The script argument defines the script to execute in the form of a function body. The value returned by that function will be returned to the client. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that define a WebElement reference will be converted to the corresponding DOM element. Likewise, any WebElements in the script result will be returned to the client as WebElement JSON objects.

func (Session) ExecuteScriptAsync

func (s Session) ExecuteScriptAsync(script string, args []interface{}) ([]byte, error)

Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be asynchronous and must signal that is done by invoking the provided callback, which is always provided as the final argument to the function. The value to this callback will be returned to the client. Asynchronous script commands may not span page loads. If an unload event is fired while waiting for a script result, an error should be returned to the client. The script argument defines the script to execute in teh form of a function body. The function will be invoked with the provided args array and the values may be accessed via the arguments object in the order specified. The final argument will always be a callback function that must be invoked to signal that the script has finished. Arguments may be any JSON-primitive, array, or JSON object. JSON objects that define a WebElement reference will be converted to the corresponding DOM element. Likewise, any WebElements in the script result will be returned to the client as WebElement JSON objects.

func (Session) FindElement

func (s Session) FindElement(using FindElementStrategy, value string) (WebElement, error)

Search for an element on the page, starting from the document root.

func (Session) FindElements

func (s Session) FindElements(using FindElementStrategy, value string) ([]WebElement, error)

Search for multiple elements on the page, starting from the document root.

func (Session) FocusOnFrame

func (s Session) FocusOnFrame(frameId interface{}) error

Change focus to another frame on the page.

func (Session) FocusOnWindow

func (s Session) FocusOnWindow(name string) error

Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute.

func (Session) FocusParentFrame

func (s Session) FocusParentFrame() error

Change focus back to parent frame

func (Session) Forward

func (s Session) Forward() error

Navigate forwards in the browser history, if possible.

func (Session) GetActiveElement

func (s Session) GetActiveElement() (WebElement, error)

Get the element on the page that currently has focus.

func (Session) GetAlertText

func (s Session) GetAlertText() (string, error)

Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog.

func (Session) GetCapabilities

func (s Session) GetCapabilities() Capabilities

Retrieve the capabilities of the specified session.

func (Session) GetCookies

func (s Session) GetCookies() ([]Cookie, error)

Retrieve all cookies visible to the current page.

func (Session) GetCurrentWindowHandle

func (s Session) GetCurrentWindowHandle() WindowHandle

func (Session) GetGeoLocation

func (s Session) GetGeoLocation() (GeoLocation, error)

Get the current geo location.

func (Session) GetHTML5CacheStatus

func (s Session) GetHTML5CacheStatus() (HTML5CacheStatus, error)

Get the status of the html5 application cache.

func (Session) GetOrientation

func (s Session) GetOrientation() (ScreenOrientation, error)

Get the current browser orientation.

func (Session) GetUrl

func (s Session) GetUrl() (string, error)

Retrieve the URL of the current page.

func (Session) IMEActivate

func (s Session) IMEActivate(engine string) error

Make an engines that is available (appears on the list returned by getAvailableEngines) active.

func (Session) IMEActiveEngine

func (s Session) IMEActiveEngine() (string, error)

Get the name of the active IME engine.

func (Session) IMEAvailableEngines

func (s Session) IMEAvailableEngines() ([]string, error)

List all available engines on the machine.

func (Session) IMEDeactivate

func (s Session) IMEDeactivate() error

De-activates the currently-active IME engine.

func (Session) IsIMEActivated

func (s Session) IsIMEActivated() (bool, error)

Indicates whether IME input is active at the moment (not if it's available).

func (Session) LocalStorageClear

func (s Session) LocalStorageClear() error

Clear the storage.

func (Session) LocalStorageGetKey

func (s Session) LocalStorageGetKey(key string) (string, error)

Get the storage item for the given key.

func (Session) LocalStorageGetKeys

func (s Session) LocalStorageGetKeys() ([]string, error)

Get all keys of the storage.

func (Session) LocalStorageRemoveKey

func (s Session) LocalStorageRemoveKey(key string) error

Remove the storage item for the given key.

func (Session) LocalStorageSetKey

func (s Session) LocalStorageSetKey(key, value string) error

Set the storage item for the given key.

func (Session) LocalStorageSize

func (s Session) LocalStorageSize() (int, error)

Get the number of items in the storage.

func (Session) Log

func (s Session) Log(logType string) ([]LogEntry, error)

Get the log for a given log type.

func (Session) LogTypes

func (s Session) LogTypes() ([]string, error)

Get available log types.

func (Session) MoveTo

func (s Session) MoveTo(element WebElement, xoffset, yoffset int) error

Move the mouse by an offset of the specificed element. If no element is specified, the move is relative to the current mouse cursor. If an element is provided but no offset, the mouse will be moved to the center of the element. If the element is not visible, it will be scrolled into view.

func (Session) Refresh

func (s Session) Refresh() error

Refresh the current page.

func (Session) Screenshot

func (s Session) Screenshot() ([]byte, error)

Take a screenshot of the current page.

func (Session) SendKeysOnActiveElement

func (s Session) SendKeysOnActiveElement(sequence string) error

Send a sequence of key strokes to the active element.

func (Session) SessionStorageClear

func (s Session) SessionStorageClear() error

Clear the storage.

func (Session) SessionStorageGetKey

func (s Session) SessionStorageGetKey(key string) (string, error)

Get the storage item for the given key.

func (Session) SessionStorageGetKeys

func (s Session) SessionStorageGetKeys() ([]string, error)

Get all keys of the storage.

func (Session) SessionStorageRemoveKey

func (s Session) SessionStorageRemoveKey(key string) error

Remove the storage item for the given key.

func (Session) SessionStorageSetKey

func (s Session) SessionStorageSetKey(key, value string) error

Set the storage item for the given key.

func (Session) SessionStorageSize

func (s Session) SessionStorageSize() (int, error)

Get the number of items in the storage.

func (Session) SetAlertText

func (s Session) SetAlertText(text string) error

Sends keystrokes to a JavaScript prompt() dialog.

func (Session) SetCookie

func (s Session) SetCookie(cookie Cookie) error

Set a cookie.

func (Session) SetGeoLocation

func (s Session) SetGeoLocation(location GeoLocation) error

Set the current geo location.

func (Session) SetOrientation

func (s Session) SetOrientation(orientation ScreenOrientation) error

Set the browser orientation.

func (Session) SetTimeouts

func (s Session) SetTimeouts(typ string, ms int) error

Configure the amount of time that a particular type of operation can execute for before they are aborted and a |Timeout| error is returned to the client. Valid values are: "script" for script timeouts, "implicit" for modifying the implicit wait timeout and "page load" for setting a page load timeout.

func (Session) SetTimeoutsAsyncScript

func (s Session) SetTimeoutsAsyncScript(ms int) error

Set the amount of time, in milliseconds, that asynchronous scripts executed by ExecuteScriptAsync() are permitted to run before they are aborted and a |Timeout| error is returned to the client.

func (Session) SetTimeoutsImplicitWait

func (s Session) SetTimeoutsImplicitWait(ms int) error

Set the amount of time the driver should wait when searching for elements. When searching for a single element, the driver should poll the page until an element is found or the timeout expires, whichever occurs first. When searching for multiple elements, the driver should poll the page until at least one element is found or the timeout expires, at which point it should return an empty list. If this command is never sent, the driver should default to an implicit wait of 0ms.

func (Session) Source

func (s Session) Source() (string, error)

Get the current page source.

func (Session) Title

func (s Session) Title() (string, error)

Get the current page title.

func (Session) TouchClick

func (s Session) TouchClick(element WebElement) error

Single tap on the touch enabled device.

func (Session) TouchDoubleClick

func (s Session) TouchDoubleClick(element WebElement) error

Double tap on the touch screen using finger motion events.

func (Session) TouchDown

func (s Session) TouchDown(x, y int) error

Finger down on the screen.

func (Session) TouchFlick

func (s Session) TouchFlick(element WebElement, xoffset, yoffset, speed int) error

Flick on the touch screen using finger motion events. This flickcommand starts at a particulat screen location.

func (Session) TouchFlickAnywhere

func (s Session) TouchFlickAnywhere(xspeed, yspeed int) error

Flick on the touch screen using finger motion events. Use this flick command if you don't care where the flick starts on the screen.

func (Session) TouchLongClick

func (s Session) TouchLongClick(element WebElement) error

Long press on the touch screen using finger motion events.

func (Session) TouchMove

func (s Session) TouchMove(x, y int) error

Finger move on the screen.

func (Session) TouchScroll

func (s Session) TouchScroll(element WebElement, xoffset, yoffset int) error

Scroll on the touch screen using finger based motion events.

func (Session) TouchUp

func (s Session) TouchUp(x, y int) error

Finger up on the screen.

func (Session) Url

func (s Session) Url(url string) error

Navigate to a new URL.

func (Session) WebElementFromId

func (s Session) WebElementFromId(id string) WebElement

func (Session) WindowHandle

func (s Session) WindowHandle() (WindowHandle, error)

Retrieve the current window handle.

func (Session) WindowHandles

func (s Session) WindowHandles() ([]WindowHandle, error)

Retrieve the list of all window handles available to the session.

type Size

type Size struct {
	Width  int
	Height int
}

type StackFrame

type StackFrame struct {
	FileName   string
	ClassName  string
	MethodName string
	LineNumber int
}

type Status

type Status struct {
	Build Build
	OS    OS
}

Server details.

type WebDriver

type WebDriver interface {
	//Start webdriver service
	Start() error
	//Stop webdriver service
	Stop() error
	//Query the server's status.
	Status() (*Status, error)
	//Create a new session.
	NewSession(desired, required Capabilities) (*Session, error)
	//Returns a list of the currently active sessions.
	Sessions() ([]Session, error)
	// contains filtered or unexported methods
}

type WebDriverCore

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

func (WebDriverCore) Start

func (w WebDriverCore) Start() error

func (WebDriverCore) Status

func (w WebDriverCore) Status() (*Status, error)

Query the server's status.

func (WebDriverCore) Stop

func (w WebDriverCore) Stop() error

type WebElement

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

func (WebElement) Clear

func (e WebElement) Clear() error

Clear a TEXTAREA or text INPUT element's value.

func (WebElement) Click

func (e WebElement) Click() error

Click on an element.

func (WebElement) Equal

func (e WebElement) Equal(element WebElement) (bool, error)

Test if two element IDs refer to the same DOM element.

func (WebElement) FindElement

func (e WebElement) FindElement(using FindElementStrategy, value string) (WebElement, error)

Search for an element on the page, starting from the identified element.

func (WebElement) FindElements

func (e WebElement) FindElements(using FindElementStrategy, value string) ([]WebElement, error)

Search for multiple elements on the page, starting from the identified element.

func (WebElement) GetAttribute

func (e WebElement) GetAttribute(name string) (string, error)

Get the value of an element's attribute.

func (WebElement) GetCssProperty

func (e WebElement) GetCssProperty(name string) (string, error)

Query the value of an element's computed CSS property.

func (WebElement) GetLocation

func (e WebElement) GetLocation() (Position, error)

Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. The element's coordinates are returned as a JSON object with x and y properties.

func (WebElement) GetLocationInView

func (e WebElement) GetLocationInView() (Position, error)

Determine an element's location on the screen once it has been scrolled into view.

Note: This is considered an internal command and should only be used to determine an element's location for correctly generating native events.

func (WebElement) IsDisplayed

func (e WebElement) IsDisplayed() (bool, error)

Determine if an element is currently displayed.

func (WebElement) IsEnabled

func (e WebElement) IsEnabled() (bool, error)

Determine if an element is currently enabled.

func (WebElement) IsSelected

func (e WebElement) IsSelected() (bool, error)

Determine if an OPTION element, or an INPUT element of type checkbox or radiobutton is currently selected.

func (WebElement) Name

func (e WebElement) Name() (string, error)

Query for an element's tag name.

func (WebElement) SendKeys

func (e WebElement) SendKeys(sequence string) error

Send a sequence of key strokes to an element.

func (WebElement) Size

func (e WebElement) Size() (Size, error)

Determine an element's size in pixels.

func (WebElement) Submit

func (e WebElement) Submit() error

Submit a FORM element.

func (WebElement) Text

func (e WebElement) Text() (string, error)

Returns the visible text for the element.

type WindowHandle

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

func (WindowHandle) GetPosition

func (w WindowHandle) GetPosition() (Position, error)

Get the position of the specified window.

func (WindowHandle) GetSize

func (w WindowHandle) GetSize() (Size, error)

Get the size of the specified window.

func (WindowHandle) MaximizeWindow

func (w WindowHandle) MaximizeWindow() error

Maximize the specified window if not already maximized.

func (WindowHandle) SetPosition

func (w WindowHandle) SetPosition(position Position) error

Change the position of the specified window.

func (WindowHandle) SetSize

func (w WindowHandle) SetSize(size Size) error

Change the size of the specified window.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL