selenium

package module
v0.0.0-...-e84564e Latest Latest
Warning

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

Go to latest
Published: Dec 28, 2018 License: MIT Imports: 22 Imported by: 0

README

This is forked from tebeka/selenium.Add action chains features like python selenium and used for personal purpose. Origin and issue, please follow the link tebeka/selenium:

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/djykissyou/selenium
package main

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

	"github.com/djykissyou/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!\n")
		}
	`)
	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.
}
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 (
	LeftButton = iota
	MiddleButton
	RightButton
)

Mouse buttons.

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

func SetDebug(debug bool)

SetDebug sets debug mode

Types

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"`
}

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 Point

type Point struct {
	X, Y int
}

Point is a 2D point.

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"`
	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 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

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 JavaPath

func JavaPath(path string) ServiceOption

JavaPath specifies the path to the JRE for a Selenium service.

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

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

	// MoveBy move the mouse
	MoveBy(xOffset, yOffset int) error
	// VoidCommand for direct use of webdriver protocol
	VoidCommand(urlTemplate string, params interface{}) 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 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)
	// Rect get the element X,Y,Height,width
	Rect() (*rect, 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
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