Interface WebDriver
-
- All Implemented Interfaces:
-
java.io.Closeable,java.lang.AutoCloseable
public interface WebDriver implements Closeable
WebDriver defines a concise interface to visit and interact with web pages, all actions and behaviors are optimized to mimic real people as closely as possible, such as scrolling, clicking, typing text, dragging and dropping, etc.
The methods in this interface fall into three categories:
Control of the browser itself
Selection of textContent and attributes of Elements
Interact with the webpage
Key methods:
navigateTo: open a page.
scrollDown: scroll down on a web page to fully load the page, most modern webpages support lazy loading using ajax tech, where the page content only starts to load when it is scrolled into view.
pageSource: retrieve the source code of a webpage.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public enumWebDriver.StateLifetime status TODO: move lifetime status to AbstractWebDriver
-
Method Summary
Modifier and Type Method Description abstract JvmWebDriverjvm()Returns a JvmWebDriver to support other JVM languages, such as java, clojure, scala, and so on, the other JVM languages might have difficulty to handle kotlin suspend methods. abstract UnitaddInitScript(String script)Adds a script which would be evaluated in one of the following scenarios: Whenever the page is navigated.
abstract UnitaddBlockedURLs(List<String> urls)Blocks resource URLs from loading. abstract UnitaddProbabilityBlockedURLs(List<String> urls)Block resource URL loading with a certain probability. abstract UnitnavigateTo(String url)Returns the main resource response. abstract UnitnavigateTo(NavigateEntry entry)Returns the response of the main resource. abstract UnitsetTimeouts(BrowserSettings browserSettings)abstract StringcurrentUrl()Returns a string representing the current URL that the browser is looking at. abstract Stringlocation()In javascript, the window.location, ordocument.location, is a read-only property returns a Location object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL.abstract StringbaseURI()In javascript, the baseURI is a property of Node, it's the absolute base URL of the document containing the node. abstract StringpageSource()Returns the source of the last loaded page. abstract Map<String, Object>mainRequestHeaders()abstract List<Map<String, String>>mainRequestCookies()abstract List<Map<String, String>>getCookies()abstract UnitdeleteCookies(String name)Deletes browser cookies with matching name. abstract UnitdeleteCookies(String name, String url, String domain, String path)Deletes browser cookies with matching name and url or domain/path pair. abstract UnitclearBrowserCookies()Clears browser cookies. abstract UnitbringToFront()Brings page to front (activates tab). abstract LongwaitForSelector(String selector)Returns when element specified by selector satisfies {@code state} option. abstract LongwaitForSelector(String selector, Long timeoutMillis)Returns when element specified by selector satisfies {@code state} option. abstract LongwaitForSelector(String selector, Duration timeout)abstract LongwaitForNavigation()abstract LongwaitForNavigation(Long timeoutMillis)abstract LongwaitForNavigation(Duration timeout)abstract WebDriverwaitForPage(String url, Duration timeout)abstract Booleanexists(String selector)BooleanisHidden(String selector)abstract BooleanisVisible(String selector)Booleanvisible(String selector)abstract BooleanisChecked(String selector)abstract Unitfocus(String selector)abstract Unittype(String selector, String text)abstract Unitclick(String selector, Integer count)abstract UnitclickTextMatches(String selector, String pattern, Integer count)UnitclickMatches(String selector, String pattern, Integer count)Use clickTextMatches instead abstract UnitclickMatches(String selector, String attrName, String pattern, Integer count)abstract StringclickNthAnchor(Integer n, String rootSelector)abstract Unitcheck(String selector)abstract Unituncheck(String selector)abstract UnitscrollTo(String selector)abstract UnitscrollDown(Integer count)abstract UnitscrollUp(Integer count)abstract UnitscrollToTop()abstract UnitscrollToBottom()abstract UnitscrollToMiddle(Float ratio)abstract UnitmouseWheelDown(Integer count, Double deltaX, Double deltaY, Long delayMillis)abstract UnitmouseWheelUp(Integer count, Double deltaX, Double deltaY, Long delayMillis)abstract UnitmoveMouseTo(Double x, Double y)abstract UnitmoveMouseTo(String selector, Integer deltaX, Integer deltaY)abstract UnitdragAndDrop(String selector, Integer deltaX, Integer deltaY)abstract StringouterHTML()Returns the document's HTML markup. abstract StringouterHTML(String selector)Returns the node's HTML markup. abstract StringfirstText(String selector)Returns the node's text content. abstract List<String>allTexts(String selector)Returns the nodes' text contents. abstract StringfirstAttr(String selector, String attrName)Returns the node's attribute name. abstract List<String>allAttrs(String selector, String attrName)Returns the nodes' attribute names. abstract Objectevaluate(String expression)Executes JavaScript in the context of the currently selected frame or window. abstract JsEvaluationevaluateDetail(String expression)Executes JavaScript in the context of the currently selected frame or window. abstract ObjectevaluateSilently(String expression)Executes JavaScript in the context of the currently selected frame or window. abstract StringcaptureScreenshot(String selector)This method scrolls element into view if needed, and then ake a screenshot of the element. abstract StringcaptureScreenshot(RectD rect)abstract PointDclickablePoint(String selector)Calculate the clickable point of an element located by selector. abstract RectDboundingBox(String selector)Return the bounding box of an element located by selector. abstract ConnectionnewSession()Create a new Jsoup session with the last page's context, which means, the same headers and cookies. abstract ConnectionnewJsoupSession()Create a new Jsoup session with the last page's context, which means, the same headers and cookies. abstract Connection.ResponseloadJsoupResource(String url)Load the url as a resource with Jsoup rather than browser rendering, with the last page's context, which means, the same headers and cookies. abstract NetworkResourceResponseloadResource(String url)Load url as a resource without browser rendering, with the last page's context, which means, the same headers and cookies. abstract Unitpause()Force the page pauses all navigations and PENDING resource fetches. UnitstopLoading()abstract Unitstop()Force the page stop all navigations and RELEASES all resources. abstract Unitterminate()Force the page stop all navigations and RELEASES all resources. abstract Unitquit()Quits this driver, closing every associated window. abstract UnitawaitTermination()Wait until the tab is terminated and closed. abstract Unitfree()Mark the driver as free, so it can be used to fetch a new page. abstract UnitstartWork()Mark the driver as working, so it can not be used to fetch another page. abstract Unitretire()Mark the driver as retired, so it can not be used to fetch any page, and should be quit as soon as possible. abstract Unitcancel()Mark the driver as canceled, so the fetch process should return as soon as possible, and the fetch result should be dropped. abstract IntegergetId()The unique driver id. abstract StringgetName()The driver name. abstract BrowsergetBrowser()The browser of the driver. abstract NavigateEntrygetNavigateEntry()The current navigation entry. abstract UnitsetNavigateEntry(NavigateEntry navigateEntry)The current navigation entry. abstract NavigateHistorygetNavigateHistory()The navigation history. abstract BrowserTypegetBrowserType()The browser type. abstract BooleangetSupportJavascript()Indicates whether the driver supports javascript. abstract BooleanisMockedPageSource()Indicate whether the page source is mocked. abstract BooleanisRecovered()Whether the driver is recovered from the browser's tab list. abstract UnitsetRecovered(Boolean isRecovered)Whether the driver is recovered from the browser's tab list. abstract BooleanisReused()Whether the driver is recovered and is reused to serve new tasks. abstract UnitsetReused(Boolean isReused)Whether the driver is recovered and is reused to serve new tasks. abstract AtomicReference<WebDriver.State>getState()The driver status. abstract Map<String, Object>getData()The associated data. abstract InstantgetLastActiveTime()The time of the last action. abstract DurationgetIdleTimeout()The idle timeout. abstract UnitsetIdleTimeout(Duration idleTimeout)The idle timeout. BooleanisIdle()abstract DurationgetWaitForElementTimeout()The timeout to wait for some object. abstract UnitsetWaitForElementTimeout(Duration waitForElementTimeout)The timeout to wait for some object. abstract BooleanisInit()abstract BooleanisReady()abstract BooleanisFree()abstract BooleanisWorking()abstract BooleanisRetired()abstract BooleanisQuit()abstract BooleanisCanceled()abstract BooleanisCrashed()abstract StringgetSessionId()Function1<String, Long>getDelayPolicy()abstract Map<String, Object>getMainRequestHeaders()abstract List<Map<String, String>>getMainRequestCookies()abstract IntegergetMainResponseStatus()abstract StringgetMainResponseStatusText()abstract Map<String, Object>getMainResponseHeaders()-
-
Method Detail
-
jvm
abstract JvmWebDriver jvm()
Returns a JvmWebDriver to support other JVM languages, such as java, clojure, scala, and so on, the other JVM languages might have difficulty to handle kotlin suspend methods.
-
addInitScript
abstract Unit addInitScript(String script)
Adds a script which would be evaluated in one of the following scenarios:
Whenever the page is navigated.
The script is evaluated after the document was created but before any of its scripts were run. This is useful to amend the JavaScript environment, e.g. to seed Math.random.
This function should be invoked before a navigation, usually in an onWillNavigate event handler.
- Parameters:
script- Javascript source code to add.
-
addBlockedURLs
abstract Unit addBlockedURLs(List<String> urls)
Blocks resource URLs from loading.
- Parameters:
urls- URL patterns to block.
-
addProbabilityBlockedURLs
abstract Unit addProbabilityBlockedURLs(List<String> urls)
Block resource URL loading with a certain probability.
- Parameters:
urls- URL patterns to block.
-
navigateTo
abstract Unit navigateTo(String url)
Returns the main resource response. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
- Parameters:
url- URL to navigate page to.
-
navigateTo
abstract Unit navigateTo(NavigateEntry entry)
Returns the response of the main resource. In case of multiple redirects, the navigation will resolve with the first non-redirect response.
- Parameters:
entry- NavigateEntry to navigate page to.
-
setTimeouts
abstract Unit setTimeouts(BrowserSettings browserSettings)
-
currentUrl
abstract String currentUrl()
Returns a string representing the current URL that the browser is looking at.
If the browser failed to return a proper url, return the url to navigate.
-
location
abstract String location()
In javascript, the
window.location, ordocument.location, is a read-only property returns a Location object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL.To retrieve just the URL as a string, the read-only
document.URLproperty can also be used.
-
baseURI
abstract String baseURI()
In javascript, the baseURI is a property of Node, it's the absolute base URL of the document containing the node. A baseURI is used to resolve relative URLs.
The base URL is determined as follows:
By default, the base URL is the location of the document (as determined by window.location).
If the document has an
<base>element, its href attribute is used.
-
pageSource
abstract String pageSource()
Returns the source of the last loaded page. If the page has been modified after loading (for example, by Javascript) there is no guarantee that the returned text is that of the modified page.
TODO: distinguish pageSource and outerHTML
-
mainRequestHeaders
@Deprecated(message = "Getter is available", replaceWith = @ReplaceWith(imports = {}, expression = "mainRequestHeaders")) abstract Map<String, Object> mainRequestHeaders()
-
mainRequestCookies
@Deprecated(message = "Getter is available", replaceWith = @ReplaceWith(imports = {}, expression = "mainRequestCookies")) abstract List<Map<String, String>> mainRequestCookies()
-
getCookies
abstract List<Map<String, String>> getCookies()
-
deleteCookies
abstract Unit deleteCookies(String name)
Deletes browser cookies with matching name.
- Parameters:
name- Name of the cookies to remove.
-
deleteCookies
abstract Unit deleteCookies(String name, String url, String domain, String path)
Deletes browser cookies with matching name and url or domain/path pair.
- Parameters:
name- Name of the cookies to remove.url- If specified, deletes all the cookies with the given name where domain and path match provided URL.domain- If specified, deletes only cookies with the exact domain.path- If specified, deletes only cookies with the exact path.
-
clearBrowserCookies
abstract Unit clearBrowserCookies()
Clears browser cookies.
-
bringToFront
abstract Unit bringToFront()
Brings page to front (activates tab).
-
waitForSelector
abstract Long waitForSelector(String selector)
Returns when element specified by selector satisfies {@code state} option.
-
waitForSelector
abstract Long waitForSelector(String selector, Long timeoutMillis)
Returns when element specified by selector satisfies {@code state} option. Returns the time remaining until timeout.
-
waitForSelector
abstract Long waitForSelector(String selector, Duration timeout)
-
waitForNavigation
abstract Long waitForNavigation()
-
waitForNavigation
abstract Long waitForNavigation(Long timeoutMillis)
-
waitForNavigation
abstract Long waitForNavigation(Duration timeout)
-
waitForPage
abstract WebDriver waitForPage(String url, Duration timeout)
-
clickTextMatches
abstract Unit clickTextMatches(String selector, String pattern, Integer count)
-
clickMatches
@Deprecated(message = "Inappropriate name", replaceWith = @ReplaceWith(imports = {}, expression = "clickTextMatches(selector, pattern, count")) Unit clickMatches(String selector, String pattern, Integer count)
Use clickTextMatches instead
-
clickMatches
abstract Unit clickMatches(String selector, String attrName, String pattern, Integer count)
-
clickNthAnchor
abstract String clickNthAnchor(Integer n, String rootSelector)
-
scrollDown
abstract Unit scrollDown(Integer count)
-
scrollToTop
abstract Unit scrollToTop()
-
scrollToBottom
abstract Unit scrollToBottom()
-
scrollToMiddle
abstract Unit scrollToMiddle(Float ratio)
-
mouseWheelDown
abstract Unit mouseWheelDown(Integer count, Double deltaX, Double deltaY, Long delayMillis)
-
mouseWheelUp
abstract Unit mouseWheelUp(Integer count, Double deltaX, Double deltaY, Long delayMillis)
-
moveMouseTo
abstract Unit moveMouseTo(Double x, Double y)
-
moveMouseTo
abstract Unit moveMouseTo(String selector, Integer deltaX, Integer deltaY)
-
dragAndDrop
abstract Unit dragAndDrop(String selector, Integer deltaX, Integer deltaY)
-
firstAttr
abstract String firstAttr(String selector, String attrName)
Returns the node's attribute name.
-
allAttrs
abstract List<String> allAttrs(String selector, String attrName)
Returns the nodes' attribute names.
-
evaluate
abstract Object evaluate(String expression)
Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.
- Parameters:
expression- Javascript expression to evaluate
-
evaluateDetail
@Beta() abstract JsEvaluation evaluateDetail(String expression)
Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.
- Parameters:
expression- Javascript expression to evaluate
-
evaluateSilently
abstract Object evaluateSilently(String expression)
Executes JavaScript in the context of the currently selected frame or window. The script fragment provided will be executed as the body of an anonymous function.
All possible exceptions are suppressed and do not throw.
- Parameters:
expression- Javascript expression to evaluate
-
captureScreenshot
abstract String captureScreenshot(String selector)
This method scrolls element into view if needed, and then ake a screenshot of the element.
-
captureScreenshot
abstract String captureScreenshot(RectD rect)
-
clickablePoint
abstract PointD clickablePoint(String selector)
Calculate the clickable point of an element located by selector. If the element does not exist, or is not clickable, returns null.
-
boundingBox
abstract RectD boundingBox(String selector)
Return the bounding box of an element located by selector. If the element does not exist, returns null.
-
newSession
@Deprecated(message = "Inappropriate name", replaceWith = @ReplaceWith(imports = {}, expression = "newJsoupSession()")) abstract Connection newSession()
Create a new Jsoup session with the last page's context, which means, the same headers and cookies.
-
newJsoupSession
abstract Connection newJsoupSession()
Create a new Jsoup session with the last page's context, which means, the same headers and cookies.
-
loadJsoupResource
abstract Connection.Response loadJsoupResource(String url)
Load the url as a resource with Jsoup rather than browser rendering, with the last page's context, which means, the same headers and cookies.
-
loadResource
abstract NetworkResourceResponse loadResource(String url)
Load url as a resource without browser rendering, with the last page's context, which means, the same headers and cookies.
-
pause
abstract Unit pause()
Force the page pauses all navigations and PENDING resource fetches. If the page loading stops, the user can still interact with the page, and therefore resources can continue to load.
-
stopLoading
@Deprecated(message = "Inappropriate name", replaceWith = @ReplaceWith(imports = {}, expression = "pause")) Unit stopLoading()
-
stop
abstract Unit stop()
Force the page stop all navigations and RELEASES all resources. Interaction with the stop page results in undefined behavior and the results should not be trusted.
If a web driver stops, it can later be used to visit new pages.
-
terminate
abstract Unit terminate()
Force the page stop all navigations and RELEASES all resources. If a web driver is terminated, it should not be used any more and should be quit as soon as possible.
-
quit
@Deprecated(message = "Inappropriate name", replaceWith = @ReplaceWith(imports = {}, expression = "close()")) abstract Unit quit()
Quits this driver, closing every associated window.
-
awaitTermination
abstract Unit awaitTermination()
Wait until the tab is terminated and closed.
-
startWork
abstract Unit startWork()
Mark the driver as working, so it can not be used to fetch another page.
-
retire
abstract Unit retire()
Mark the driver as retired, so it can not be used to fetch any page, and should be quit as soon as possible.
-
cancel
abstract Unit cancel()
Mark the driver as canceled, so the fetch process should return as soon as possible, and the fetch result should be dropped.
-
getBrowser
abstract Browser getBrowser()
The browser of the driver. The browser defines methods and events to manipulate a real browser.
-
getNavigateEntry
abstract NavigateEntry getNavigateEntry()
The current navigation entry.
-
setNavigateEntry
abstract Unit setNavigateEntry(NavigateEntry navigateEntry)
The current navigation entry.
-
getNavigateHistory
abstract NavigateHistory getNavigateHistory()
The navigation history.
-
getBrowserType
abstract BrowserType getBrowserType()
The browser type.
-
getSupportJavascript
abstract Boolean getSupportJavascript()
Indicates whether the driver supports javascript. Web drivers such as MockDriver do not support javascript.
-
isMockedPageSource
abstract Boolean isMockedPageSource()
Indicate whether the page source is mocked.
-
isRecovered
abstract Boolean isRecovered()
Whether the driver is recovered from the browser's tab list.
-
setRecovered
abstract Unit setRecovered(Boolean isRecovered)
Whether the driver is recovered from the browser's tab list.
-
isReused
abstract Boolean isReused()
Whether the driver is recovered and is reused to serve new tasks.
-
setReused
abstract Unit setReused(Boolean isReused)
Whether the driver is recovered and is reused to serve new tasks.
-
getState
abstract AtomicReference<WebDriver.State> getState()
The driver status.
-
getLastActiveTime
abstract Instant getLastActiveTime()
The time of the last action.
-
getIdleTimeout
abstract Duration getIdleTimeout()
The idle timeout.
-
setIdleTimeout
abstract Unit setIdleTimeout(Duration idleTimeout)
The idle timeout.
-
getWaitForElementTimeout
abstract Duration getWaitForElementTimeout()
The timeout to wait for some object.
-
setWaitForElementTimeout
abstract Unit setWaitForElementTimeout(Duration waitForElementTimeout)
The timeout to wait for some object.
-
isCanceled
abstract Boolean isCanceled()
-
getSessionId
abstract String getSessionId()
-
getDelayPolicy
Function1<String, Long> getDelayPolicy()
-
getMainRequestHeaders
abstract Map<String, Object> getMainRequestHeaders()
-
getMainRequestCookies
abstract List<Map<String, String>> getMainRequestCookies()
-
getMainResponseStatus
abstract Integer getMainResponseStatus()
-
getMainResponseStatusText
abstract String getMainResponseStatusText()
-
getMainResponseHeaders
abstract Map<String, Object> getMainResponseHeaders()
-
-
-