Selenium My Notes
Selenium My Notes
String Methods
String length() ->>> length of the string
String charAt()->>> returns a char value at the given index number
String concat()->>> combines specified string at the end of this string
String contains()->>> returns true if chars are found in the string
String startsWith()->>> checks if this string starts with given prefix
String endsWith()->>> checks if this string ends with given suffix
String equals()->>> compares the contents of two given strings
String indexOf()->>> returns index of given character value or substring
String isEmpty()->>> checks if this string is empty
String replace()->>> returns a string replacing all the old char to new char
String substring()->>> returns a part of the string
String toCharArray()->>> converts this string into character array
String toLowerCase()->>> returns the string in lowercase letter
String toUpperCase()->>> returns the string in uppercase letter
String trim()->>> eliminates leading and trailing spaces
Every element does not have an id -> static id, unique name, unique link text. For those
elements we need to build xpath to find and then perform actions on them.
Whatever we use to find an element, id, name, xpath, css -> It should always be unique. It
should only find one matching node unless we want to capture a list of elements
Syntax:
tag[attribute='value']
“#” -> Id
“.” -> Class
Appending Classes
.class1.class2.class3 -> Until we find a unique element
Finding Children
fieldset -> 10 matching nodes
Fieldset>table
fieldset>#product -> One matching node
fieldset>button -> One matching node
Fieldset>a fieldset>input#name
Whatever we use to find an element, id, name, xpath -> It should always be unique. It
should only find one matching node unless we want to capture a list of elements.
Single slash ‘/’ anywhere in xpath signifies to look for the element immediately inside the
parent element.
Double slash ‘//’ signifies to look for any child or nested child element inside the parent
element.
Syntax: //tag[@attribute='value']
Parent
Syntax: xpath-to-some-element//parent
Preceding Sibling
Syntax: xpath-to-some-element//preceding-sibling
Following Sibling
Syntax: xpath-to-some-element//following-sibling
if (!isChecked) {
radioButtons.get(i).click();
Thread.sleep(2000);
}}}
7. Working with drop down
public void testDropdown() throws Exception {
driver.get(baseUrl);
WebElement element = driver.findElement(By.id("carselect"));
Select sel = new Select(element);
Thread.sleep(2000);
System.out.println("Select Benz by value");
sel.selectByValue("benz");
Thread.sleep(2000);
System.out.println("Select Honda by index");
sel.selectByIndex(2);
Thread.sleep(2000);
System.out.println("Select BMW by visible text");
sel.selectByVisibleText("BMW");
Thread.sleep(2000);
System.out.println("Print the list of all options");
List<WebElement> options = sel.getOptions();
int size = options.size();
driver.get(baseUrl);
Thread.sleep(2000);
System.out.println("Select orange by value");
sel.selectByValue("orange");
Thread.sleep(2000);
System.out.println("De-select orange by value");
sel.deselectByValue("orange");
Thread.sleep(2000);
System.out.println("Select peach by index");
sel.selectByIndex(2);
Thread.sleep(2000);
sel.selectByVisibleText("Apple");
Thread.sleep(2000);
System.out.println("Print all selected options");
List<WebElement> selectedOptions = sel.getAllSelectedOptions();
for (WebElement option : selectedOptions) {
System.out.println(option.getText());
}
Thread.sleep(2000);
System.out.println("De-select all selected options");
sel.deselectAll();
}
driver.get(baseUrl1);
Thread.sleep(3000);
Thread.sleep(3000);
// Added code to scroll up because the element was hiding behind the top
navigation menu
// You will learn about scrolling
js.executeScript("window.scrollBy(0, -190);");
WebElement showButton = driver.findElement(By.id("show-textbox"));
showButton.click();
System.out.println("Clicked on show button");
System.out.println("Text Box Displayed: " + textBox.isDisplayed());
}
10. Profiles
What is Profile?
File where Firefox saves your personal information such as bookmarks, passwords, and user
preferences.
Multiple Firefox profiles can exist, each containing a separate set of preferences.
It is nice to make a separate profile for automation, so as to not disturb your usual browser
settings.
A profile should be lightweight - it should only have settings, plugins that you need for
automation.
Windows
1. At the top of the Firefox window, click on the File menu and then select Exit.
2. Press ‘ + R’ or click on the Windows Start Menu (bottom left button) and then select Run.
3. In the Run dialog box, type in: ‘firefox.exe -p' and then Click OK.
If the Profile Manager window does not appear, it may be possible that Firefox is opened in
the background. It needs to be closed; you can open the Task Manager to kill the process. If
it still does not open then you may need to specify the full path of the Firefox program.
"/Users/atomar/Documents/workspace_personal/libs/geckodriver");
String baseURL = "http://www.letskodeit.com";
WebDriver driver;
Implicit Wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
Explicit Wait
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(3));
ExpectedConditions.visibilityOfElementLocated(By.id("user_email")));
Interview Questions
What are the different types of waits available in Selenium WebDriver With Java
Programming Language?
Implicit Wait: If elements are not immediately available, an implicit wait tells Web Driver to
poll the DOM for a certain amount of time. The default setting is 0. Once set, the implicit
wait is set for the duration of the Web Driver object. This means that we can tell Selenium
WebDriver that we would like it to wait for a certain amount of time before throwing an
exception that it cannot find the element on the page.
Explicit Wait: It is the custom one. It will be used if we want the execution to wait for some
time until some condition achieved. There can be instance when a particular element takes
more than a minute to load. In that case you definitely not like to set a huge time to Implicit
wait, as if you do this your browser will going to wait for the same time for every element.
To avoid that situation you can simply put a separate time on the required element only. By
following this your browser implicit wait time would be short for every element and it would
be large for specific element.
@Before
public void setUp() throws Exception {
driver = new ChromeDriver();
baseUrl = "https://www.facebook.com/";
// Maximize the browser's window
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
@Test
public void testScreenshots() throws Exception {
driver.get(baseUrl);
driver.findElement(By.xpath("//input[@data-
testid='royal_login_button']")).click();
}
@After
public void tearDown() throws Exception {
String filename = getRandomString(10) + ".png";
String directory = System.getProperty("user.dir") + "//screenshots//";
File sourceFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(sourceFile, new File(directory + filename));
driver.quit();
}
// Finding element
// WebElement textBox = driver.findElement(By.id("name"));
WebElement textBox = (WebElement) js.executeScript("return
document.getElementById('name');");
// Size of window
long height = (Long) js.executeScript("return window.innerHeight;");
long width = (Long) js.executeScript("return window.innerWidth;");
// Scroll Down
js.executeScript("window.scrollBy(0, 1900);");
// Scroll Up
js.executeScript("window.scrollBy(0, -1900);");
js.executeScript("window.scrollBy(0, -190);");
//click on element
WebElement checkBoxElement = driver.findElement(By.id("bmwcheck"));
js.executeScript("arguments[0].click();", checkBoxElement);
15. Switch
Window
// Get the handle
String parentHandle = driver.getWindowHandle();
Iframe:
// Switch to frame by Id
driver.switchTo().frame("courses-iframe");
16. Ale
Alert alert = driver.switchTo().alert();
alert.accept();
alert.dismiss();
driver.findElement(By.id("openwindow")).sendKeys(Keys.COMMAND + "a");
driver.findElement(By.id("openwindow")).sendKeys(Keys.chord(Keys.COMMAND, "a"));
Advantages of Log4j
• Log4j allows you to have a very good logging infrastructure with minimal efforts.
• Allows categorizing logs at different logging levels (Trace, Debug, Info, Warn, Error and
Fatal).
• Provides control to format the output of the logs.
• It has multiple appenders styles, which allows to direct logs to different outputs styles like
a file, console or a database.
• Logging can be set at runtime using configuration files.
Logger This is a class, which helps you log information at different logging levels.
Appenders Appenders are objects, which help Logger objects write logs to different outputs.
Appenders can specify a file, console or a database as the output location.
Layouts Layout class helps us define how the log information should appear in the outputs.
https://logging.apache.org/log4j/2.0/download.html
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core/2.7
https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api/2.7
Log4j will check the system property “log4j.configurationFile” for the configuration file path.
In case no system property is defined the configuration order takes below precedence:
• Property ConfigurationFactory will look for log4j2-test.properties in the classpath.
• YAML ConfigurationFactory will look for log4j2-test.yaml or log4j2-test.yml in the
classpath.
• JSON ConfigurationFactory will look for log4j2-test.jsn or log4j2-test.json in the classpath.
• XML ConfigurationFactory will look for log4j2-test.xml in the classpath.
• Property ConfigurationFactory will look for log4j2.properties on the classpath
• YAML ConfigurationFactory will look for log4j2.yml or log4j2.yaml in the classpath.
• JSON ConfigurationFactory will look for log4j2.jsn or log4j2.json in the classpath.
• XML ConfigurationFactory will look for log4j2.xml in the classpath.
• If no configuration file was provided, the DefaultConfiguration takes place and that would
lead you for set of default behaviors:
o Root logger will be used.
o Root logger level will be set to ERROR.
o Root logger will propagate logging messages into console.
o PatternLayout is set to be %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
• ALL
• TRACE
• DEBUG
• INFO
• WARN
• ERROR
• FATAL
private static final Logger log = LogManager.getLogger(LoggingDemo.class.getName());
log.debug("Debug Message Logged");
log.error("Error Message Logged");
log.fatal("Fatal Message Logged");
TestNG is a testing framework inspired from JUnit and NUnit with more functionality added
to make execution more efficient and powerful. It is an open source automated testing
framework.
TestNG eliminates most of the limitations of the older framework and gives the developer
the ability to write more flexible and powerful tests with help of easy annotations, grouping,
sequencing & parameterizing.
Annotations in TestNG
@BeforeSuite: Method with this annotation will run before all tests in the test suite
@AfterSuite: Method with this annotation will run after all tests in the test suite
@BeforeTest: Method with this annotation will run before each and every test method with
tag in xml file
@AfterTest: Method with this annotation will run after each and every test method with tag
in xml file
@BeforeClass: Method with this annotation will run before first test method in current class
@AfterClass: Method with this annotation will run after last test method in current class
@BeforeMethod: Method with this annotation will run before each test method
@AfterMethod: Method with this annotation will run after each test method
@Test: The annotated method is a part of a test case.
@DataProvider(name="inputs")
{"bmw", "m3"},
{"audi", "a6"},
{"benz", "c300"}
};
@Test(dataProvider="inputs")