Class AbstractWebDriver
-
- All Implemented Interfaces:
-
ai.platon.pulsar.skeleton.crawl.fetch.driver.WebDriver,java.io.Closeable,java.lang.AutoCloseable,kotlin.Comparable
public abstract class AbstractWebDriver implements Comparable<AbstractWebDriver>, WebDriver
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description public enumAbstractWebDriver.StateThe state of the driver.
State.INIT: The driver is initialized.
State.READY: The driver is ready to work.
State.WORKING: The driver is working.
State.RETIRED: The driver is retired and should be quit as soon as possible.
State.QUIT: The driver is quit.
-
Field Summary
Fields Modifier and Type Field Description private final IntegerparentSidprivate final BrowserSettingssettingsprivate final FloatresourceBlockProbabilityprivate final List<String>blockedURLsprivate final List<String>probabilisticBlockedURLsprivate final BooleanisConnectableprivate final BrowserChatModelchatModelprivate final Objectimplementationprivate final SnapshotServicesnapshotServiceprivate DurationidleTimeoutprivate InstantlastActiveTimeprivate final BooleanisIdleprivate final BooleanisActiveprivate final BooleanisInitprivate final BooleanisReadyprivate final BooleanisWorkingprivate final BooleanisRetiredprivate final BooleanisQuitprivate final BooleanisCanceledprivate final BooleanisCrashedprivate final Stringstatusprivate final BooleanisMockedPageSourceprivate BooleanisRecoveredprivate BooleanisReusedprivate BooleanisRecyclableprivate BooleanignoreDOMFeaturesprivate final <Error class: unknown class>nameprivate NavigateEntrynavigateEntryprivate final NavigateHistorynavigateHistoryprivate final <Error class: unknown class>delayPolicyprivate final <Error class: unknown class>timeoutPolicyprivate final List<WebDriver>framesprivate WebDriveropenerprivate final Set<WebDriver>outgoingPagesprivate final Map<String, Object>dataprivate final Map<String, Object>mainRequestHeadersprivate final List<Map<String, String>>mainRequestCookiesprivate final IntegermainResponseStatusprivate final StringmainResponseStatusTextprivate final Map<String, Object>mainResponseHeadersprivate final Stringguidprivate final AbstractBrowserbrowserprivate final Integeridprivate final BrowserTypebrowserType
-
Constructor Summary
Constructors Constructor Description AbstractWebDriver(String guid, AbstractBrowser browser, Integer id)
-
Method Summary
Modifier and Type Method Description IntegergetParentSid()The parent driver id. final BrowserSettingsgetSettings()final FloatgetResourceBlockProbability()final List<String>getBlockedURLs()final List<String>getProbabilisticBlockedURLs()final BooleanisConnectable()BrowserChatModelgetChatModel()ObjectgetImplementation()SnapshotServicegetSnapshotService()final DurationgetIdleTimeout()Idle timeout before a READY driver is considered stale and eligible for recycling/retirement. final UnitsetIdleTimeout(Duration idleTimeout)Idle timeout before a READY driver is considered stale and eligible for recycling/retirement. final InstantgetLastActiveTime()final UnitsetLastActiveTime(Instant lastActiveTime)final BooleanisIdle()final BooleanisActive()final BooleanisInit()final BooleanisReady()final BooleanisWorking()final BooleanisRetired()final BooleanisQuit()final BooleanisCanceled()final BooleanisCrashed()final StringgetStatus()BooleanisMockedPageSource()True if pageSource is a mocked/fake value (e.g. final BooleanisRecovered()Driver participated in a recovery workflow (e.g. final UnitsetRecovered(Boolean isRecovered)Driver participated in a recovery workflow (e.g. final BooleanisReused()Driver reused from pool after previous task. final UnitsetReused(Boolean isReused)Driver reused from pool after previous task. final BooleanisRecyclable()If recyclable the driver returns to a standby pool post-task; else it remains dedicated until retired. final UnitsetRecyclable(Boolean isRecyclable)If recyclable the driver returns to a standby pool post-task; else it remains dedicated until retired. final BooleangetIgnoreDOMFeatures()Skip DOM feature computation if true (performance optimization for pure interaction tasks). final UnitsetIgnoreDOMFeatures(Boolean ignoreDOMFeatures)Skip DOM feature computation if true (performance optimization for pure interaction tasks). <Error class: unknown class>getName()NavigateEntrygetNavigateEntry()Navigate entry for the current page (URL + metadata). UnitsetNavigateEntry(NavigateEntry navigateEntry)Navigate entry for the current page (URL + metadata). NavigateHistorygetNavigateHistory()History of navigation entries. <Error class: unknown class>getDelayPolicy()Delay policy (per action random delay ranges) derived from browser settings. <Error class: unknown class>getTimeoutPolicy()Timeout policy (per action max durations) derived from browser settings. List<WebDriver>getFrames()Child frame drivers (if any) WebDrivergetOpener()Page opener driver (if window opened by script / click) UnitsetOpener(WebDriver opener)Page opener driver (if window opened by script / click) Set<WebDriver>getOutgoingPages()Pages opened from this page (window.open, target=_blank, etc. Map<String, Object>getData()Arbitrary contextual data store. final Map<String, Object>getMainRequestHeaders()final List<Map<String, String>>getMainRequestCookies()final IntegergetMainResponseStatus()final StringgetMainResponseStatusText()final Map<String, Object>getMainResponseHeaders()StringgetGuid()The guid of the driver. AbstractBrowsergetBrowser()The browser of the driver. IntegergetId()The driver id, starts with 1. final Unitfree()Transition to READY (available for assignment). final UnitstartWork()Transition to WORKING (exclusive usage). final Unitretire()Mark for disposal after current task. final Unitcancel()Request cooperative cancellation of current task (best-effort). UnitaddInitScript(String script)Adds a script which would be evaluated whenever the page is navigated. Unitnavigate(String url)Navigates current page to the given URL. Unitreload()Reloads the current page. StringcurrentUrl()Returns a string representing the current URL that the browser is looking at. Stringurl()The URL read-only property of the Document interface returns the document location as a string. StringdocumentURI()Returns the document location as a string. StringbaseURI()Returns the document's baseURI. Stringtitle()Returns the title of the current page. Stringreferrer()The referrer property returns the URI of the page that linked to this page. ModelResponsechat(String prompt, String selector)Interact with an AI model using the context of the element selected by selector. <T extends Any> Tevaluate(String expression, T defaultValue)Executes JavaScript and returns the result, or defaultValue if the result is null or incompatible. <T extends Any> TevaluateValue(String expression, T defaultValue)Executes JavaScript and returns the result as a JSON-serializable value, or defaultValue if null/incompatible. BooleanisVisible(String selector)Returns whether the element is visible. BooleanisChecked(String selector)Returns whether the element is checked. DoublescrollDown(Integer count)The current page frame scrolls down for count times. DoublescrollUp(Integer count)The current page frame scrolls up for count times. DoublescrollBy(Double pixels, Boolean smooth)Scrolls the current page frame vertically by the given number of pixels. DoublescrollToTop()The current page frame scrolls to the top. DoublescrollToBottom()The current page frame scrolls to the bottom. DoublescrollToMiddle(Double ratio)The current page frame scrolls to the middle. DoublescrollToViewport(Double n, Boolean smooth)Scrolls to the position of the n-th viewport. StringouterHTML()Returns the document's HTML markup. StringouterHTML(String selector)Returns the node's HTML markup, the node is located by selector. StringtextContent(String selector)Returns the text content of the document or a specific element. Map<String, String>extract(Map<String, String> fields)Extracts multiple fields from the page using CSS selectors. StringselectFirstTextOrNull(String selector)Returns the node's text content, the node is located by selector. List<String>selectTextAll(String selector)Returns a list of text contents of all the elements matching the specified selector within the page. StringselectFirstAttributeOrNull(String selector, String attrName)Returns the node's attribute value, the node is located by selector, the attribute is attrName. Map<String, String>selectAttributes(String selector)Returns the node's attribute values, the node is located by selector. List<String>selectAttributeAll(String selector, String attrName, Integer start, Integer limit)Returns the nodes' attribute values, the nodes are located by selector, the attribute is attrName. UnitsetAttribute(String selector, String attrName, String attrValue)Set the attribute of an element located by selector. UnitsetAttributeAll(String selector, String attrName, String attrValue)Set the attribute of all elements matching the CSS query. StringselectFirstPropertyValueOrNull(String selector, String propName)Returns the node's property value, the node is located by selector, the property is propName. List<String>selectPropertyValueAll(String selector, String propName, Integer start, Integer limit)Returns the nodes' property values, the nodes are located by selector, the property is propName. UnitsetProperty(String selector, String propName, String propValue)Set the property of an element located by selector. UnitsetPropertyAll(String selector, String propName, String propValue)Set the property of all elements matching the CSS query. List<Hyperlink>selectHyperlinks(String selector, Integer offset, Integer limit)Find hyperlinks in elements matching the selector. List<GeoAnchor>selectAnchors(String selector, Integer offset, Integer limit)Select anchors (link + coordinates) – placeholder implementation until util binding available. List<String>selectImages(String selector, Integer offset, Integer limit)Select image URLs (abs:src) – placeholder implementation. UnitclickTextMatches(String selector, String pattern, Integer count)This method clicks an element with selector whose text content matches pattern, and then focuses it. UnitclickMatches(String selector, String attrName, String pattern, Integer count)This method clicks an element with selector whose attribute name is attrName and value matches pattern, and then focuses it. Unitcheck(String selector)This method check an element with selector. Unituncheck(String selector)This method uncheck an element with selector. DurationwaitForSelector(String selector)Wait until the element identified by the selector becomes present in the DOM or timeout. DurationwaitForSelector(String selector, SuspendFunction0<Unit> action)Wait for the element identified by the selector to become present in the DOM, or until timeout. DurationwaitForNavigation(String oldUrl)Wait until the current url changes or timeout. DurationwaitForNavigation(String oldUrl, Duration timeout)Wait until the current url changes or timeout. DurationwaitUntil(SuspendFunction0<Boolean> predicate)Wait until the predicate returns true. DurationwaitUntil(Duration timeout, SuspendFunction0<Boolean> predicate)Wait until the predicate returns true. final LongrandomDelayMillis(String action, IntRange fallback)Generate a random delay in milliseconds for an action. final Durationtimeout(String action, Duration fallback)ConnectionnewJsoupSession()Create a new Jsoup session with the last page's context, which means, the same headers and cookies. Connection.ResponseloadJsoupResource(String url)Load the url as a resource with Jsoup rather than browser rendering, with the last page's context. NetworkResourceResponseloadResource(String url)Load the url as a resource without browser rendering, with the last page's context. Booleanequals(Object other)IntegerhashCode()IntegercompareTo(AbstractWebDriver other)StringtoString()Unitterminate()UnitawaitTermination()Unitclose()final BooleancheckState(String action)-
Methods inherited from class ai.platon.pulsar.skeleton.crawl.fetch.driver.WebDriver
addBlockedURLs, ariaSnapshot, ariaSnapshot, boundingBox, bringToFront, captureScreenshot, captureScreenshot, captureScreenshot, clearBrowserCookies, click, click, clickablePoint, dblclick, dblclick, delay, delay, delay, deleteCookies, dialogAccept, dialogDismiss, drag, dragAndDrop, evaluate, evaluateDetail, evaluateValue, evaluateValue, evaluateValueDetail, evaluateValueDetail, exists, fill, focus, getBrowserType, getCookies, goBack, goForward, hover, isHidden, keyDown, keyUp, mouseDown, mouseMove, mouseUp, mouseWheel, mouseWheelDown, mouseWheelUp, moveMouseTo, moveMouseTo, nanoDOMTree, navigate, navigateTo, navigateTo, open, pageSource, pause, press, querySelectorAll, resize, screenshot, screenshot, screenshot, scrollTo, selectOption, selectOption, stop, type, upload, waitForFunction, waitForNavigation, waitForPage, waitForSelector, waitForSelector, waitForSelector, waitForSelector, waitUntil -
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
-
-
Constructor Detail
-
AbstractWebDriver
AbstractWebDriver(String guid, AbstractBrowser browser, Integer id)
-
-
Method Detail
-
getParentSid
Integer getParentSid()
The parent driver id. The id is unique in process scope.
-
getSettings
final BrowserSettings getSettings()
-
getResourceBlockProbability
final Float getResourceBlockProbability()
-
getBlockedURLs
final List<String> getBlockedURLs()
-
getProbabilisticBlockedURLs
final List<String> getProbabilisticBlockedURLs()
-
isConnectable
final Boolean isConnectable()
-
getChatModel
BrowserChatModel getChatModel()
-
getImplementation
Object getImplementation()
-
getSnapshotService
SnapshotService getSnapshotService()
-
getIdleTimeout
final Duration getIdleTimeout()
Idle timeout before a READY driver is considered stale and eligible for recycling/retirement.
-
setIdleTimeout
final Unit setIdleTimeout(Duration idleTimeout)
Idle timeout before a READY driver is considered stale and eligible for recycling/retirement.
-
getLastActiveTime
final Instant getLastActiveTime()
-
setLastActiveTime
final Unit setLastActiveTime(Instant lastActiveTime)
-
isCanceled
final Boolean isCanceled()
-
isMockedPageSource
Boolean isMockedPageSource()
True if pageSource is a mocked/fake value (e.g. offline / synthetic content).
-
isRecovered
final Boolean isRecovered()
Driver participated in a recovery workflow (e.g. auto relaunch) after crash.
-
setRecovered
final Unit setRecovered(Boolean isRecovered)
Driver participated in a recovery workflow (e.g. auto relaunch) after crash.
-
isRecyclable
final Boolean isRecyclable()
If recyclable the driver returns to a standby pool post-task; else it remains dedicated until retired.
-
setRecyclable
final Unit setRecyclable(Boolean isRecyclable)
If recyclable the driver returns to a standby pool post-task; else it remains dedicated until retired.
-
getIgnoreDOMFeatures
final Boolean getIgnoreDOMFeatures()
Skip DOM feature computation if true (performance optimization for pure interaction tasks).
-
setIgnoreDOMFeatures
final Unit setIgnoreDOMFeatures(Boolean ignoreDOMFeatures)
Skip DOM feature computation if true (performance optimization for pure interaction tasks).
-
getName
<Error class: unknown class> getName()
-
getNavigateEntry
NavigateEntry getNavigateEntry()
Navigate entry for the current page (URL + metadata).
-
setNavigateEntry
Unit setNavigateEntry(NavigateEntry navigateEntry)
Navigate entry for the current page (URL + metadata).
-
getNavigateHistory
NavigateHistory getNavigateHistory()
History of navigation entries.
-
getDelayPolicy
<Error class: unknown class> getDelayPolicy()
Delay policy (per action random delay ranges) derived from browser settings.
-
getTimeoutPolicy
<Error class: unknown class> getTimeoutPolicy()
Timeout policy (per action max durations) derived from browser settings.
-
getOutgoingPages
Set<WebDriver> getOutgoingPages()
Pages opened from this page (window.open, target=_blank, etc.)
-
getMainRequestHeaders
final Map<String, Object> getMainRequestHeaders()
-
getMainRequestCookies
final List<Map<String, String>> getMainRequestCookies()
-
getMainResponseStatus
final Integer getMainResponseStatus()
-
getMainResponseStatusText
final String getMainResponseStatusText()
-
getMainResponseHeaders
final Map<String, Object> getMainResponseHeaders()
-
getBrowser
AbstractBrowser getBrowser()
The browser of the driver. The browser defines methods and events to manipulate a real browser.
-
free
final Unit free()
Transition to READY (available for assignment). Resets cancellation/crash flags. Must only be called after INIT or WORKING states.
-
startWork
final Unit startWork()
Transition to WORKING (exclusive usage). Resets cancellation/crash flags.
-
addInitScript
Unit addInitScript(String script)
Adds a script which would be evaluated whenever the page is navigated. @mcp
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.
-
navigate
Unit navigate(String url)
Navigates current page to the given URL. @mcp
driver.navigate("https://www.example.com") driver.waitForNavigation()- Parameters:
url- URL to navigate page to.
-
reload
Unit reload()
Reloads the current page. @mcp
This method should trigger a reload of the current page, similar to how a user would refresh the page in a browser.
-
currentUrl
String currentUrl()
Returns a string representing the current URL that the browser is looking at. @mcp
The current url is always the main frame's
document.documentURIif the browser succeed to return it, and is displayed in the browser's address bar.If the browser failed to return a proper url, returns the passed in url to navigate, just like a real user enter a url in the address bar but the browser failed to load the page.
NOTE: the url can be non-standard, for example:
about:blank chrome://newtab chrome://settings
see ai.platon.cdt.kt.protocol.types.page.NavigationEntry.userTypedURL
- Returns:
A string containing the URL of the document, or the passed in url to navigate.
-
url
String url()
The URL read-only property of the Document interface returns the document location as a string. @mcp
This property equals to javascript
document.URL. Thedocument.URLproperty returns the same value. Thedocument.documentURIproperty can be used on any document types, while thedocument.URLproperty can only be used on HTML documents.- Returns:
A string containing the URL of the document
-
documentURI
String documentURI()
Returns the document location as a string. @mcp
This property equals to javascript
document.documentURI.The
document.URLproperty which returns the same value. Thedocument.documentURIproperty can be used on any document types, while thedocument.URLproperty can only be used on HTML documents.- Returns:
The document's documentURI.
-
baseURI
String baseURI()
Returns the document's baseURI. @mcp
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.
- Returns:
The document's baseURI.
-
referrer
String referrer()
The referrer property returns the URI of the page that linked to this page. @mcp
The value is an empty string if the user navigated to the page directly (not through a link, but, for example, by using a bookmark).
Inside an <iframe>, the referrer will initially be set to the same value as the href of the parent window's Window.location.
- Returns:
The document's referrer.
-
chat
ModelResponse chat(String prompt, String selector)
Interact with an AI model using the context of the element selected by selector. @mcp
The AI model receives the element's content and structure as context along with the provided prompt.
- Parameters:
prompt- The question or instruction for the AI model.selector- The CSS selector of the element to use as context.- Returns:
A ModelResponse containing the model's answer.
-
evaluate
<T extends Any> T evaluate(String expression, T defaultValue)
Executes JavaScript and returns the result, or defaultValue if the result is null or incompatible. @mcp
- Parameters:
expression- The JavaScript expression to evaluate.defaultValue- The value to return if evaluation fails or returns null.- Returns:
The evaluation result or defaultValue.
-
evaluateValue
<T extends Any> T evaluateValue(String expression, T defaultValue)
Executes JavaScript and returns the result as a JSON-serializable value, or defaultValue if null/incompatible. @mcp
- Parameters:
expression- The JavaScript expression to evaluate.defaultValue- The value to return if evaluation fails or returns null.- Returns:
The evaluation result or defaultValue.
-
isVisible
Boolean isVisible(String selector)
Returns whether the element is visible. @mcp
driver.isVisible("input[name='q']")- Parameters:
selector-The selector of the element to check.
- Returns:
Whether the element is visible.
-
isChecked
Boolean isChecked(String selector)
Returns whether the element is checked. @mcp
driver.isChecked("input[name='agree']")- Parameters:
selector-The selector of the element to check.
- Returns:
Whether the element is checked.
-
scrollDown
Double scrollDown(Integer count)
The current page frame scrolls down for count times. @mcp
driver.scrollDown(3)TODO: use mouseWheel instead
- Parameters:
count- The times to scroll down.
-
scrollUp
Double scrollUp(Integer count)
The current page frame scrolls up for count times. @mcp
driver.scrollUp(3)TODO: use mouseWheel instead
- Parameters:
count- The times to scroll up.
-
scrollBy
Double scrollBy(Double pixels, Boolean smooth)
Scrolls the current page frame vertically by the given number of pixels. @mcp
Positive values scroll down, negative values scroll up. The target position is clamped to the scrollable range 0, scrollHeight - viewportHeight.
When smooth is true a deterministic, step‑wise scrolling algorithm is used (instead of relying on the browser's native smooth scrolling) for higher stability: it issues incremental
window.scrollTo()calls and waits for the viewport to settle after each step. This reduces race conditions with lazy‑loaded content or async layout changes and yields more predictable final positions.Typical usage:
// Scroll down 200px smoothly (default) driver.scrollBy() // Scroll up 500px immediately driver.scrollBy(-500.0, smooth = false) // Scroll down one viewport height, smooth val y = driver.scrollBy(driver.viewportHeight(), smooth = true)- Parameters:
pixels- The delta in pixels to scroll; positive scrolls down, negative scrolls up.smooth- Whether to perform a deterministic smooth scrolling sequence.- Returns:
The final vertical scroll offset (window.scrollY) after scrolling.
-
scrollToTop
Double scrollToTop()
The current page frame scrolls to the top. @mcp
driver.scrollToTop()
-
scrollToBottom
Double scrollToBottom()
The current page frame scrolls to the bottom. @mcp
driver.scrollToBottom()
-
scrollToMiddle
Double scrollToMiddle(Double ratio)
The current page frame scrolls to the middle. @mcp
driver.scrollToMiddle(0.2) driver.scrollToMiddle(0.5) driver.scrollToMiddle(0.8)- Parameters:
ratio- The ratio of the page to scroll to, 0.0 means the top, 1.0 means the bottom.
-
scrollToViewport
Double scrollToViewport(Double n, Boolean smooth)
Scrolls to the position of the n-th viewport.
- Parameters:
n- Viewport index (1 represents the first screen)smooth- Whether to use smooth scrolling- Returns:
Actual scrollY pixel value after scrolling
-
outerHTML
String outerHTML()
Returns the document's HTML markup. @mcp
val html = driver.outerHTML()If the document does not exist, returns null.
- Returns:
The HTML markup of the document.
-
outerHTML
String outerHTML(String selector)
Returns the node's HTML markup, the node is located by selector. @mcp
If the node does not exist, returns null.
val html = driver.outerHTML("h2.title")- Parameters:
selector- The selector to locate the node.- Returns:
The HTML markup of the node.
-
textContent
String textContent(String selector)
Returns the text content of the document or a specific element. @mcp
If selector is null, returns the text content of the entire document (usually
document.body.innerText). If selector is provided, returns the text content of the first matching element.If the document or element does not exist, returns null.
val bodyText = driver.textContent() val titleText = driver.textContent("h1.title")- Parameters:
selector- The CSS selector of the element.- Returns:
The text content, or null if not found.
-
extract
Map<String, String> extract(Map<String, String> fields)
Extracts multiple fields from the page using CSS selectors. @mcp
- Parameters:
fields- A map where keys are field names and values are CSS selectors.- Returns:
A map containing the extracted text content for each field. Values are null if the selector matches nothing.
-
selectFirstTextOrNull
String selectFirstTextOrNull(String selector)
Returns the node's text content, the node is located by selector. @mcp
If the node does not exist, returns null.
val text = driver.selectFirstTextOrNull("h2.title")- Parameters:
selector- The selector to locate the node.- Returns:
The text content of the node.
-
selectTextAll
List<String> selectTextAll(String selector)
Returns a list of text contents of all the elements matching the specified selector within the page. @mcp
If no elements match the selector, returns an empty list.
val texts = driver.selectTextAll("h2")- Parameters:
selector- The selector to locate the nodes.- Returns:
The text contents of the nodes.
-
selectFirstAttributeOrNull
String selectFirstAttributeOrNull(String selector, String attrName)
Returns the node's attribute value, the node is located by selector, the attribute is attrName. @mcp
If the node does not exist, or the attribute does not exist, returns null.
val classes = driver.selectFirstAttributeOrNull("h2.title", "class")- Parameters:
selector- The selector to locate the node.attrName- The attribute name to retrieve.- Returns:
The attribute value of the node.
-
selectAttributes
Map<String, String> selectAttributes(String selector)
Returns the node's attribute values, the node is located by selector. @mcp
If the node do not exist, or the attribute does not exist, returns an empty list.
val classes = driver.selectAttributes("h2.title", "class")- Parameters:
selector- The selector to locate the nodes.- Returns:
The attribute pairs of the nodes.
-
selectAttributeAll
List<String> selectAttributeAll(String selector, String attrName, Integer start, Integer limit)
Returns the nodes' attribute values, the nodes are located by selector, the attribute is attrName. @mcp
If the nodes do not exist, or the attribute does not exist, returns an empty list.
val classes = driver.selectAttributeAll("h2.title", "class")- Parameters:
selector- The selector to locate the nodes.attrName- The attribute name to retrieve.start- The offset of the first node to select.limit- The maximum number of nodes to select.- Returns:
The attribute values of the nodes.
-
setAttribute
Unit setAttribute(String selector, String attrName, String attrValue)
Set the attribute of an element located by selector. @mcp
driver.setAttribute("h2.title", "class", "header")- Parameters:
selector- The CSS query to select an element.attrName- The attribute name to set.attrValue- The attribute value to set.
-
setAttributeAll
Unit setAttributeAll(String selector, String attrName, String attrValue)
Set the attribute of all elements matching the CSS query. @mcp
driver.setAttributeAll("h2.title", "class", "header")- Parameters:
selector- The CSS query to select elements.attrName- The attribute name to set.attrValue- The attribute value to set.
-
selectFirstPropertyValueOrNull
String selectFirstPropertyValueOrNull(String selector, String propName)
Returns the node's property value, the node is located by selector, the property is propName. @mcp
If the node does not exist, or the property does not exist, returns null.
val classes = driver.selectFirstPropertyOrNull("input#input", "value")- Parameters:
selector- The selector to locate the node.propName- The property name to retrieve.- Returns:
The property value of the node.
-
selectPropertyValueAll
List<String> selectPropertyValueAll(String selector, String propName, Integer start, Integer limit)
Returns the nodes' property values, the nodes are located by selector, the property is propName. @mcp
If the nodes do not exist, or the property does not exist, returns an empty list.
val classes = driver.selectPropertyAll("input#input", "value")- Parameters:
selector- The selector to locate the nodes.propName- The property name to retrieve.start- The offset of the first node to select.limit- The maximum number of nodes to select.- Returns:
The property values of the nodes.
-
setProperty
Unit setProperty(String selector, String propName, String propValue)
Set the property of an element located by selector. @mcp
driver.setProperty("input#input", "value")- Parameters:
selector- The CSS query to select an element.propName- The property name to set.propValue- The property value to set.
-
setPropertyAll
Unit setPropertyAll(String selector, String propName, String propValue)
Set the property of all elements matching the CSS query. @mcp
driver.setPropertyAll("input#input", "value")- Parameters:
selector- The CSS query to select elements.propName- The property name to set.propValue- The property value to set.
-
selectHyperlinks
List<Hyperlink> selectHyperlinks(String selector, Integer offset, Integer limit)
Find hyperlinks in elements matching the selector. NOTE: Currently constructs absolute URLs by concatenating baseURI and raw href; TODO: robust resolution & abs: support.
- Parameters:
selector- The CSS query to select elements.offset- The offset of the first element to select.limit- The maximum number of elements to select.
-
selectAnchors
List<GeoAnchor> selectAnchors(String selector, Integer offset, Integer limit)
Select anchors (link + coordinates) – placeholder implementation until util binding available.
- Parameters:
selector- The CSS query to select elements.offset- The offset of the first element to select.limit- The maximum number of elements to select.
-
selectImages
List<String> selectImages(String selector, Integer offset, Integer limit)
Select image URLs (abs:src) – placeholder implementation.
- Parameters:
selector- The CSS query to select elements.offset- The offset of the first element to select.limit- The maximum number of elements to select.
-
clickTextMatches
Unit clickTextMatches(String selector, String pattern, Integer count)
This method clicks an element with selector whose text content matches pattern, and then focuses it. @mcp
If there's no element matching selector, or the element's text content doesn't match pattern, nothing to do.
driver.clickTextMatches("button", "submit")TODO: use playwright style selector which supports text matching, for example:
button:has-text("submit")- Parameters:
selector-A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
pattern- The pattern to match the text content.count- The number of times to click.
-
clickMatches
Unit clickMatches(String selector, String attrName, String pattern, Integer count)
This method clicks an element with selector whose attribute name is attrName and value matches pattern, and then focuses it. @mcp
If there's no element matching selector, or the element has no attribute attrName, or the element's attribute value doesn't match pattern, nothing to do.
driver.clickMatches("button", "type", "submit")- Parameters:
selector-A selector of an element to focus. If there are multiple elements satisfying the selector, the first will be focused.
attrName- The attribute name to match.pattern- The pattern to match the attribute value.count- The number of times to click.
-
check
Unit check(String selector)
This method check an element with selector. If there's no element matching selector, nothing to do. @mcp
- Parameters:
selector-A selector of an element to check. If there are multiple elements satisfying the selector, the first will be checked.
-
uncheck
Unit uncheck(String selector)
This method uncheck an element with selector. If there's no element matching selector, nothing to do. @mcp
- Parameters:
selector-A selector of an element to uncheck. If there are multiple elements satisfying the selector, the first will be focused.
-
waitForSelector
Duration waitForSelector(String selector)
Wait until the element identified by the selector becomes present in the DOM or timeout. @mcp
val remainingTime = driver.waitForSelector("h2.title")- Parameters:
selector- The selector of the element to wait for.- Returns:
The remaining time until timeout when the element becomes present.
-
waitForSelector
Duration waitForSelector(String selector, SuspendFunction0<Unit> action)
Wait for the element identified by the selector to become present in the DOM, or until timeout. @mcp
This method periodically checks for the existence of the element. If the element is not found during a check, the action will be executed, such as scrolling the page down.
val remainingTime = driver.waitForSelector("h2.title") { driver.scrollDown() }- Parameters:
action- The action to execute when the element is not found.
-
waitForNavigation
Duration waitForNavigation(String oldUrl)
Wait until the current url changes or timeout. @mcp
val url = "https://www.example.com" driver.navigate(url) var remainingTime = driver.waitForNavigation() if (remainingTime 0) { driver.click("a[href='/next']") remainingTime = driver.waitForNavigation(url) }
-
waitForNavigation
Duration waitForNavigation(String oldUrl, Duration timeout)
Wait until the current url changes or timeout. @mcp
val timeout = Duration.ofSeconds(30) val url = "https://www.example.com" driver.navigate(url) var remainingTime = driver.waitForNavigation(timeout) if (remainingTime 0) { driver.click("a[href='/next']") remainingTime = driver.waitForNavigation(url, timeout) }- Parameters:
timeout- The maximum time to wait for the url to change.
-
waitUntil
Duration waitUntil(SuspendFunction0<Boolean> predicate)
Wait until the predicate returns true. @mcp
val remainingTime = driver.waitUntil { driver.exists("h2.title") }- Parameters:
predicate- The predicate to check.- Returns:
The remaining time until timeout when the predicate returns true.
-
waitUntil
Duration waitUntil(Duration timeout, SuspendFunction0<Boolean> predicate)
Wait until the predicate returns true. @mcp
val remainingTime = driver.waitUntil(Duration.ofSeconds(10)) { driver.exists("h2.title") }- Parameters:
timeout- The maximum time to wait for the predicate to return true.predicate- The predicate to check.- Returns:
The remaining time until timeout when the predicate returns true.
-
randomDelayMillis
final Long randomDelayMillis(String action, IntRange fallback)
Generate a random delay in milliseconds for an action.
- Parameters:
action- Named action bucket (fallbacks: specific -> default -> provided fallback range).fallback- Used if policy values are missing / invalid.
-
newJsoupSession
Connection newJsoupSession()
Create a new Jsoup session with the last page's context, which means, the same headers and cookies. @mcp
- Returns:
The Jsoup session.
-
loadJsoupResource
Connection.Response loadJsoupResource(String url)
Load the url as a resource with Jsoup rather than browser rendering, with the last page's context. @mcp
This means, the same headers and cookies.
- Parameters:
url- The URL to load.- Returns:
The Jsoup response.
-
loadResource
NetworkResourceResponse loadResource(String url)
Load the url as a resource without browser rendering, with the last page's context. @mcp
This means, the same headers and cookies.
- Parameters:
url- The URL to load.- Returns:
The network resource response.
-
compareTo
Integer compareTo(AbstractWebDriver other)
-
awaitTermination
Unit awaitTermination()
-
checkState
final Boolean checkState(String action)
-
-
-
-