Simplified Robotics API cheatsheet
tip
The article contains a cheatsheet for using the main Robotics Simplified API methods.
Selectors (locators)
note
Before interacting with a UI element, locate it using the $() or $$() constructions.
$(), $$()
// locating and manipulating element
def uiElement = $('.css-class')
uiElement.doubleClick()
$(byLinkText('Purchase')).click()
// navigating to hidden element
$('.TreeNode').focus()
// finding the Nth element matching given criteria
$(withText('Open', 5)).hover()
// locating focused element
def focusedEl = getFocusedElement()
if (focusedEl.getId() == 'tuk-tuk') { focusedEl().click(2) }
// using element collections
def fieldCollection = $$(byXpath("//*[@name='field-product']"))
fieldCollection.each {
println it.getText()
}
// getting element from collection
fieldCollection.last().val('butter')
def firstField = fieldCollection.first()
def sixthField = fieldCollection.get(5)
// filtering collection by condition
def readonlyCollection = fieldCollection.filter(READONLY)
def inactiveReadonlyCollection = readonlyCollection.exclude(cssClass('temp'))
// searching child elements
$(byTitle('Web Form')).find('div > table > tr:nth-child(5) > td').click()
def childRowCollection = $('#multirowTable').findAll('tr.active')
// searching parent and ancestor elements
def parentClass = $('td').parent().getAttribute('class')
def ancestorText = $('#exp-0').closest('div').text()
// alternatives to $() and $$()
getElement(byImage('https://site/img1.png'), 200, 300).click()
def abbreviations = getElements(byTagName('abbr'))
Selector types
Web:
byCssSelector // default, same as $('.selector')
byXpath
byId
byName
byClassName
byTagName
byTitle
byValue
by('attribute_name', 'attribute_name')
byAttribute('name','value')
withText
byText
byLinkText
byPartialLinkText
Desktop:
CSS selectors // $('.Button[text='Click me']')
Object selectors // $('[CLASS:Button; INSTANCE:2]')
byXpath // for Java apps only
byImage('link', offsetX, offsetY)
Opening apps and browsers
open(), openAndFocus(), openIE()
// open a website
open('https://www.wikipedia.org')
// open an application
open('calc.exe')
// open an app and switch to the newly opened window
openAndFocus('notepad.exe', 3000, 250)
// in Universal driver, you can open a specific browser
openFirefox('https://www.wikipedia.org')
openChrome('https://workfusion.com')
openIE('https://google.com/chrome/browser/desktop/index.html')
// opening new browser tabs
openLinkInNewWindow(byCssSelector('.container a.create-new'))
openLinkInNewWindow('https://automationacademy.com')
openNewWindow()
Excel, files and folders
openExcel(), Resource, downloadFileOnAgent()
// opening excel file for manipulating it
def filePath = 'C:/downloads/report.xlsx'
openExcel(filePath)
switchSheet(filePath, 'Fact')
def temp = getCell(filePath, 'B1')
// manipulating with local files and folders
def filePath = downloadFileOnAgent(s3Path)
Resource.append(filePath, '___ New Content ___', 'utf-8')
def content_utf8 = Resource.read(filePath, 'utf-8')
Resource.createDirectoryOverwrite('D:\\temp\\new\\')
// downloading and uploading files to/from RPA Server
def filePathOnAgent = downloadFileOnAgent('https://s3-path/1.csv')
downloadFileOnAgent('https://s3-path/1.csv', 'C:/Temp/new-file.csv')
byte byteFileContent = downloadFileFromAgent('C:/Temp/1.csv')
def stringFileContent = downloadTextFileFromAgent('C:/Temp/2.csv')
deleteFileOnAgent('C:/Temp/1.csv')
def textFilePath = sendToAgent('new file text content')
def binaryFilePath = sendToAgent(byteFileContent, 'D:/new/new-file.csv')
tip
- For the Excel API description, refer to Excel Class.
- For the files and folders API, Files and Folders | Resource Class.
Mouse
click(), hover(), dragAndDrop()
// clicking in different ways
$('#nav-bar').click()
$$(byTagName('p')).get(2).click(3) // or tripleClick(), doubleClick()
$('#nav-bar').contextClick()
// clicking by coordinates
mouse().click(20, 20)
mouse().wheelClick(100, 78)
mouseDown(coordinates)
mouseUp(int,int)
// moving mouse, hovering, scrolling
mouseMove(100, 500)
$('#nav-bar').hover()
$('#nav-bar').scrollTo()
$('#nav-bar').scrollDown(7) // or scrollUp(5)
// submitting forms
$('.btn__act').submit()
// clicking with offset
$('.MyMenu').click(20,135)
// drag and drop by selectors or coordinates offset
actions().dragAndDrop($(byImage("${imagePath}/source.png")), xOffset, yOffset)
.perform()
actions().clickAndHold($(byImage("${imagePath}/image.png")))
.moveToElement($(byImage("${imagePath}/image.png")))
.release($(byImage("${imagePath}/image.png")))
.perform()
actions().dragAndDrop(
$(byImage("${imagePath}/source-folder.png")),
$(byImage("${imagePath}/target-folder.png")))
.perform()
tip
See more about advanced user interactions.
Keyboard
sendKeys(), pressEnter(), Keys.chord()
// sending text
$('#input-username').sendKeys('Jimmy')
// sending multiple keys sequentially
sendKeys(Keys.DOWN, Keys.ENTER)
// sending key combinations
sendKeys(Keys.chord(Keys.CONTROL, 'a'))
// holding keys to perform complex actions
keyboard().pressKey(Keys.SHIFT)
sendKeys(Keys.DOWN, Keys.DOWN)
keyboard().releaseKey(Keys.SHIFT)
// pressing popular keys and combinations
pressCtrlC()
pressCtrlV()
pressEnter()
// combining text and action keys
sendKeys('username{Enter}')
// will type the "username" and press Enter key
// switching to raw keys mode
switchSendRawKeysMode(true)
sendKeys('username{Enter}')
// will type the "username{Enter}" string
// without pressing the Enter key
// typing into window regardless of its active language
sendKeys('{UTF 怒helloनमस्ते}')
// typing DEL 4 times
sendKeys("{DEL 4}")
tip
To learn more about Web and Desktop keystrokes, refer to SendKeys Keystrokes Guide
Conditions and assertions
should(), has(), is()
$(byXpath('//p[2]')).shouldHave(text('Hello'))
$('.loading_progress').should(DISAPPEAR)
$('input').shouldNotHave(cssClass('active'))
$('#mydiv').shouldHave(attribute('fileId'))
$(withText('Your message has been sent.')).shouldBe(VISIBLE)
$('h1').should(matchRegexp("Hello\s*John"))
$('#logoutLink').should(APPEAR)
$('#myInput').waitUntil(partialValue('John'), 5000)
$$('.errorMessage').first().shouldBe(VISIBLE, ENABLED)
$$('td').shouldHaveSize(5)
$('#errorMessage').should(APPEAR).shouldBe(ENABLED)
| Assertion | Conditions | Logical operators |
|---|---|---|
|
|
|
Windows and frames
// switching to window by its attribute
switchTo().window('[CLASS:Notepad]')
window('[TITLE:Photoshop]')
// works faster than window()
switchToExistingWindow('[CLASS:Notepad]', 100L)
// switching to window by its order
switchToLastWindow()
switchToRootWindow()
switchToPrevWindow()
switchToNextWindow()
// switching to iframe
switchTo().frame('iframeResult')
switchTo().parentFrame()
switchTo().defaultContent()
// closing window(s)
close()
closeAllAnotherWindows()
closeAllWindows()
// Changing window size
minimizeWindow()
maximizeWindow()
zoom(2.5)
// navigation in history
forward()
back()
refresh() // only for web
// Handling popups and alerts
confirm()
confirm('Do you want to exit?')
dismiss()
Timeouts and waits
// setting timeouts for different actions (milliseconds)
pageLoadTimeout(5000) // for open(), openAndFocus(), switch() - web or window
implicitlyWaitTimeout(3000) // used for finding element $(); collections $$() do not use timeout
scriptTimeout(30 * 1000) // for JavaScript or Groovy scripts
// setting all timeouts in one command
timeouts(40 * 1000)
// set timeout for explicit waits
setFluentWaitTimeout(3 * 1000)
setFluentWaitPollingInterval(200)
// check the existence of element - if it might be missing
fluentWait()
.ignoring(org.openqa.selenium.NoSuchElementException.class)
.until(ExpectedConditions.presenceOfElementLocated(byCssSelector('#new')))
// explicit wait usage, only for elements which exist
$('.demo-el').waitUntil(VISIBLE)
$('.demo-el').waitWhile(SELECTED)
Wait()
.withMessage('mesage')
.withTimeout(5, java.util.concurrent.TimeUnit.SECONDS)
.pollingEvery(500, java.util.concurrent.TimeUnit.MILLISECONDS)
.until(...)
// explicit wait with custom timeout and polling interval
$('.demo-el').waitWhile(READONLY, 3000, 200)
// pausing script execution - not recommended in production
sleep(3000)
tip
Clipboard
// copying to clipboard
selectAllTextAndCopy()
pressCtrlC()
$('p.news').tripleClick()
copySelectedText()
copyPuttyWindowText()
// getting clipboard text
def clipboard = clipboardText()
$(byXpath('//input[3]')).pressCtrlV()
// setting clipboard text
setClipboardText('new_content')
Screenshots
// desktop - using org.sikuli.script or java.awt.Robot
String path = executeGroovyScript(javaScreenshot.toString())
// browser
def screen = driver().getScreenshotAs(OutputType.BYTES) // or BASE64, FILE
def bytes = screenshotAsImage()
Get and set value
// getting value, text, attribute
def emailValue = $('#email').val() // or getValue()
def iNumber = $('#invoice-n').attr('name') //or getAttribute(), name()
def someText = $(byXpath('//p[2]')).text() // or getText()
def allPosts = $$('p.content').getTexts()
def tag = $('.btn').getTagName()
// setting value and text
$('#email').val('wf-robot@mail.com') // or setValue()
$(byXpath('//input[3]')).text('new text')
// resetting field text
$$('.nav').get(5).clear()
// getting location and coordinates
$(byImage('${imageLink}')).getRect().getWidth()
$(byImage('${imageLink}')).getLocation()
$(withText('create')).getSize()
// radio-buttons
def oRadioButton = $$(byName('occupation'))
if (oRadioButton.get(0).isSelected()) {
oRadioButton.get(1).setSelected(true)
}
// dropdowns
def optionsList = $(byId('continents'))
optionsList.selectOption(2)
optionsList.selectOptionByValue('AFR')
println optionsList.getSelectedText()
println optionsList.getSelectedValue()
println optionsList.getSelectedOption().getText()
Scripting
// executing a Groovy Script on RPA Node
def scriptResult = executeGroovyScript(console_script.toString())
// JavaScript or AutoIt
def messages = ['Hello ', 'from ']
executeScript("alert(arguments[0][0] + arguments[0][1] + arguments[1])", messages, 'JS')
// Output: "Hello from JS"
Explicitly set driver in Universal Script
<robotics-flow>
<robot name="universalDriver" driver="universal" close-on-completion="true">
<script><![CDATA[
// open a web-application in Firefox and log in
inFirefox() {
open('https://invoiceplane.workfusion.com')
$('#login').click()
$('#email').val('wf-robot@mail.com')
$('#password').val('freedom4ROBOTS')
$(byName('btn_login')).click()
}
// open a web-page in Chrome and click
inChrome() {
open('https://www.w3schools.com/')
switchTo().frame('iframeResult')
$('#demo h1').shouldHave(text('XMLHttpRequest'))
$(byText('Change Content')).click()
}
// open a web-page in Internet Explorer, enter text, and click
inIE() {
open('http://rpa-grid.s3.amazonaws.com')
$(byXpath('//input[@name='name']')).sendKeys('test')
$(byXpath('//button[@type='submit']')).click()
}
// open notepad and type text into it
inDesktop() {
open('notepad.exe')
switchTo().window('[CLASS:Notepad]')
sendKeys('foo')
}
]]></script>
</robot>
</robotics-flow>