Selenium Topics

Selenium Webdriver

Browser Tools

Firefox

FirePath

FireBug

Selenium IDE

Chrome

F12 Developer Tool

Console

To Evaluate the xpath and Css in Chrome
For Xpath -- $x('//input[@id='test']')
For Css -- $$('.classname')

Internet Explorer

Developer Tool

Webdriver Wait

Implicit Wait

driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);

Explicit Wait

WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element =wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(),'COMPOSE')]")));

ExpectedConditions

elementToBeClickable()

textToBePresentInElement()

alertIsPresent()

titleIs()

frameToBeAvailableAndSwitchToIt()

Fluent Wait

Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS).ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function() {

public WebElement apply(WebDriver driver) {

return driver.findElement(By.id("foo"));

}

});

Selenium Grid

Standalone

Standalone java -jar selenium-server-<version>.jar standalone

Default port 4444

WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub";;), capability);

Node & Hub

java -jar selenium-server-<version>.jar hub
java -jar selenium-server-<version>.jar node
java -jar selenium-server-<version>.jar node --port 5555
Node & Hub on Same machine

-browser browserName=firefox,version=3.6,maxInstances=5,platform=LINUX

Using JSON file : java -jar selenium-server-standalone.jar -role node -nodeConfig nodeconfig.json

Distributed

Event Bus: enables internal communication between different Grid components

java -jar selenium-server-<version>.jar event-bus --publish-events tcp://<event-bus-ip>:4442 --subscribe-events tcp://<event-bus-ip>:4443 --port 5557

New Session Queue: adds new session requests to a queue, which will be queried by the Distributor

java -jar selenium-server-<version>.jar sessionqueue --port 5559

Session Map: maps session IDs to the Node where the session is running

java -jar selenium-server-<version>.jar sessions --publish-events tcp://<event-bus-ip>:4442 --subscribe-events tcp://<event-bus-ip>:4443 --port 5556

Distributor: queries the New Session Queue for new session requests, and assigns them to a Node when the capabilities match. Nodes register to the Distributor the way they register to the Hub in a Hub/Node Grid.

java -jar selenium-server-<version>.jar distributor --publish-events tcp://<event-bus-ip>:4442 --subscribe-events tcp://<event-bus-ip>:4443 --sessions http://<sessions-ip>:5556 --sessionqueue http://<new-session-queue-ip>:5559 --port 5553 --bind-bus false

Router: redirects new session requests to the queue, and redirects running sessions requests to the Node running that session

java -jar selenium-server-<version>.jar router --sessions http://<sessions-ip>:5556 --distributor http://<distributor-ip>:5553 --sessionqueue http://<new-session-queue-ip>:5559 --port 4444

Node(s)

java -jar selenium-server-<version>.jar node --publish-events tcp://<event-bus-ip>:4442 --subscribe-events tcp://<event-bus-ip>:4443

Common Exceptions

ElementNotSelectableException

ElementNotVisibleException

NoAlertPresentException

NoSuchElementException

NoSuchFrameException

NoSuchWindowException

StaleElementReferenceException

TimeoutException

UnexpectedAlertPresentException

java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.ie.driver system property

WebDriverListener

EventFiringWebDriver eventDriver = new EventFiringWebDriver(remotWebdriver);
eventDriver.register(new DriverListener());

public class DriverListener implements WebDriverEventListener

onException()

beforeClickOn()

beforeChangeValueOf()

afterClickOn()

beforeFindBy()

Advance User Interaction

Browser Engine
(layout engine or rendering engine)

Selenium 4

Selenium Manager -Selenium Manager is a command-line tool implemented in Rust that provides automated driver and browser management for Selenium

Langauge bindings

JAVA

Eclipse

TestNG

testng.xml

annotations

@BeforeSuite

@AfterSuite

@BeforeTest

@AfterTest

@BeforeGroups

@AfterGroups

@BeforeClass

@AfterClass

@BeforeMethod

@AfterMethod

dataprovider

groups

Listeners

IAlterSuiteListener

IAnnotationTransformer

IConfigurationListener

IDataProviderListener

IExecutionListener

IExecutionVisualiser

IHookable

IConfigurable

IInvokedMethodListener

IClassListener

IMethodInterceptor

IDataProviderInterceptor

IReporter

ISuiteListener

ITestListener

Maven

<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.27.0</version>
</dependency>

Surefire Plugin

ANT

Jenkin

C#

Ruby

Python

JavaScript

JsonWireProtocol(OLD)/Webdriver Protocol

GET /status Query the server's current status.
POST /session Create a new session.

POST /session/:sessionId/element/:id/click Click on an element.

GET /session/:sessionId Retrieve the capabilities of the specified session.

Locator Type

ID

Class name

Name

Link Text and Partial Linktext

Xpath

Relative Xpath

//span[@class=’Email’]

//a[contains(text(),'Create an account')]

//*[@id='link-forgot-passwd']

//table//tbody//tr//td[contains(text(),'Name')]/..//input

//div[contains(text(),'From:')]/../input[1]

Searching by Class and Text
//span[contains(@class,'myclass') and text() = 'qwerty']
//span[conatins(@class,'myclass') and normalize-space(text()) ='qwerty']

Absolute Xpath

Example : /html/body/div/div[@id=’Email’]

CSS Selector

ID css=input#Email

Class css=label.classname

Attributes css=input[type=’submit’]

ID/Class & Attributes css=input#Passwd[name=’Passwod’]

Sub String

prefix css=input#Password[name^='pass'']

ends with/suffix css=input#Password[name$='rd']

Contains/Sub-String css=input#Password[name*='ss']

nav[id='primaryNav'] ul p:nth-child(2) a select an element if:
*It is a paragraph element
*It is the second child of a parent

select.attributes p:nth-of-type(2) Select the second paragraph child of a parent(less Conditional)

li:first-child, li:last-child,div div:last-of-type

PageObject Model

public class GoogleSearchPage {
@FindBy(name = "q")
private WebElement searchBox;

public void searchFor(String search)
{
searchBox.sendKeys(search);
}
}

public class UsingGoogleSearchPage {
public static void main(String[] args) {
// Create a new instance of a driver
WebDriver driver = new HtmlUnitDriver();

// Navigate to the right place
driver.get("http://www.google.com/";;);

// Create a new instance of the search page class
// and initialise any WebElement fields in it.
GoogleSearchPage page = PageFactory.initElements(driver, GoogleSearchPage.class);

// And now do the search.
page.searchFor("Cheese");
}
}

Annotations - PageFactory

@FindBy( how=How.ID,using='idofelement')

@FindBy(xpath="//div[@id='abc']")

@FindBy(id="idofelement")

@FindBys(value = { @FindBy(css = "select.availableOptions>option") })
private List<WebElement> elementList;

Alerts/Popup

JavaScripExecutor

Turn Off/On Native Events

FirefoxProfile profile = new FirefoxProfile();
profile.setEnableNativeEvents(true);
FirefoxDriver driver = new FirefoxDriver(profile);

profile.setPreference("general.useragent.override", "Mozilla/5.0 Phone user agent");
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().setSize(new Dimension(414,736));

ChromeOptions and FireFox Profile

Add extension in the browser
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("/path/to/extension.crx"));
ChromeDriver driver = new ChromeDriver(options);

Map<String, Object> chromeOptions = new Map<String, Object>();
chromeOptions.put("binary", "/usr/lib/chromium-browser/chromium-browser");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, chromeOptions);
WebDriver driver = new ChromeDriver(capabilities);