0% found this document useful (0 votes)
7 views

C- SELENIUM

The document provides a comprehensive overview of Selenium, detailing its advantages such as being open-source and supporting cross-browser testing, as well as its disadvantages including limitations to web applications and the need for programming knowledge. It covers various methods for interacting with web elements, handling alerts, and managing waits, along with TestNG annotations and exception handling. Additionally, it discusses batch and group execution, dynamic elements, and the Page Factory design pattern for improved code maintainability.

Uploaded by

rajat.kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C- SELENIUM

The document provides a comprehensive overview of Selenium, detailing its advantages such as being open-source and supporting cross-browser testing, as well as its disadvantages including limitations to web applications and the need for programming knowledge. It covers various methods for interacting with web elements, handling alerts, and managing waits, along with TestNG annotations and exception handling. Additionally, it discusses batch and group execution, dynamic elements, and the Page Factory design pattern for improved code maintainability.

Uploaded by

rajat.kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

SELENIUM

Advantages of Selenium:

 Open-source and free.


 Cross-browser testing support.
 Supports multiple programming languages.
 Cross-platform compatibility (Windows, macOS, Linux).
 Integration with DevOps tools (Jenkins, Maven, etc.).
 Parallel test execution (Selenium Grid).
 Active community support.
 Efficient automation of web applications.

Disadvantages of Selenium:

 Limited to web applications only.


 No built-in reporting.
 Requires programming knowledge.
 High maintenance for dynamic web elements.
 No official technical support.
 No native support for image-based testing.
 Difficult to automate Captcha and OTPs.
 Limited control over the browser for system-level
operations.
Locators
driver.findElement(By.id(""));
driver.findElement(By.name(""));
driver.findElement(By.className(""));
driver.findElement(By.tagName(""));
driver.findElement(By.linkText(""));
driver.findElement(By.partialLinkText(""));
driver.findElement(By.cssSelector(""));
driver.findElement(By.xpath(""));
Relative XPath :
1. xpath by Attribute: //tagname[@attribute='value']
2. xpath by Text function: //tagname[text()='textValue']
3. Contains function: //tagname[contains(text(),'partialText')]
4. Traversing xpath
5. Independent-Dependent xpath
6. Xpath by Group index
7. Normalize-space() : //tagname [ contains (normalize-space(), ‘text;)]

Dynamic Xpath -:

 // input [ contains (@class, 'input-') ]


 // button [starts-with (@id, 'btnSubmit')]
 // tag [ends-with (@attribute, 'end_value')]
 // tag [@attribute1='value1' or @attribute2='value2']
 // tag [text() = 'exact_text' ]

Methods of SearchContext-:
o findElement(), FindElements(By.arg)
Methods of WebDriver-:
o Close(), get(), getCurrentUrl(), getPageSource(),
getTitle(), getWindowHandle(),
getWindowHandles(), manage(), navigate(), quit(),
switchTo()
Methods of JavaScriptExecutor-:
o executeAsyncScript(), executeScript()
Method of TakesScreenshot-:
o getScreenshotAs()
Method of WebElement-:
Clear(), click(), getAttribute(), getCssValue(),
getLocation(), getRect(), getSize(), getTagName(),
getText(), isDisplayed(), isEnabled(), isSelected(),
sendkeys(), submit()
element.getLocation().getX();
element.getLocation().getY();

Q. Handling disable elements & scroll bar

We are using JavaScript to perform scrolling actions.


Scroll down by pixels and Scroll to an element:

JavascriptExecutor js = (JavascriptExecutor) driver;


js.executeScript("window.scrollBy(0, 500);");
js.executeScript("window.scrollTo(0, 0);");
int loc = element.getLocation().getY(); // .getX()
js.executeScript("window.scrollBy(0," + loc + ")", element);
Q. Without using sendkeys how do you send an input to a text field?

Using Selenium, we can execute JavaScript code to set a value in an input field.

JavascriptExecutor js = (JavascriptExecutor) driver;

js.executeScript("arguments[0].value='Input text';", element);

Q. How do you handle alerts, windows, and frames in Selenium?


Handle alerts using the Alert interface.
 Alert alert = driver.switchTo().alert();
 alert.accept();
 alert.dismiss();
 alert.getText();
 String text = alert.getText();
 alert.sendKeys(text);

Switch between windows


 Set<String> allWindow = driver.getWindowHandles();
 for (String window : allWindow) {
 driver.switchTo().window(window);
 String title = driver.getTitle();
 System.out.println("The window title is : " + title);
 }

Switch between frames using

 driver.switchTo().frame(0);
 driver.switchTo().defaultContent();
 driver.switchTo().parentFrame();

Read Data From Excel File

FileInputStream fis = new FileInputStream(FILE_PATH);


Workbook wb = WorkbookFactory.create(fis);
wb.getSheet(sheetName).getRow(1).getCell(1).getStringCellValue();
Write Data Excel File

FileInputStream fis = new FileInputStream(FILE_PATH);


Workbook wb = WorkbookFactory.create(fis);

wb.getSheet(sheetName).sh.getRow(1).getCell(1).setCellValue(“Hi”);
FileOutputStream fos = new FileOutputStream(FILE_PATH);
wb.write(fos);
wb.close();

Read Property Data

FileInputStream fis=new FileInputStream("FILE_PATH");


Properties prop=new Properties();
prop.load(fis);
prop.getProperty("Key");

************File Upload************
public void selectFileToUpload(WebElement fileInputElement)
{
File file = new File("./TestData/Jiviews Team.jpg");
String absolutePath = file.getAbsolutePath();
fileInputElement.sendKeys(absolutePath);
}
Q. How to take screenshot

TakesScreenshot ts = (TakesScreenshot) driver;

File source = ts.getScreenshotAs(OutputType.FILE);


File destination = new File("./Screenshot" );
FileUtils.copyFile(source, destination);

Q. Explain the concept of Waits in Selenium.


1. Implicit Wait: Waits a specified amount of time for elements to
appear before throwing an exception. It is applied globally and
affects all elements in the test.
2. Explicit Wait: In order to handle the synchronization of any method
we use explicit wait. WebDriverWait itself is called as explicit wait
because we have to specify the waiting condition explicitly.
3. Fluent Wait: It is like Explicit Wait, but checks the condition
repeatedly until a timeout.
implicitlyWait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

Explicit Wait Condition


WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));

wait.until(ExpectedConditions.elementToBeClickable(locator));
wait.until(ExpectedConditions.elementToBeSelected(locator));
wait.until(ExpectedConditions.visibilityOf((locator));
wait.until(ExpectedConditions.invisibilityOf(locator));
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
Boolean titleContains = wait.until(ExpectedConditions.titleContains("page
Title"));
Boolean title = wait.until(ExpectedConditions.titleIs("exact_title"));
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
Boolean textPresent =
wait.until(ExpectedConditions.textToBePresentInElementLocated(locator,
"expected_text"));

Q. Difference between ImplicitWait & ExplicitWait

ImplicitWait-:
 We do not specify the waiting condition explicitly.
 We can handle the synchronization of all the findElement &
findElements method.
 After the duration we get NoSuchElementException.
 Time duration can be days, hours, mins, seconds etc.

ExplicitWait-:
 We should specify the waiting condition explicitly.
 We can handle the synchronization o any method but only one at a
time.
 After the duration we get TimeOutException.
 Time duration will be only seconds.

Q. Handleing Listbox from the Select class in Selenium:

Select select=new Select(element);

select.selectByIndex(1);
select.selectByValue("value");
select.selectByVisibleText("visible Text");
select.deselectByIndex(0);
select.deselectByValue("value");
select.deselectByVisibleText("visible Text");
select.deselectAll();
select.getOptions();
select.getAllSelectedOptions();
select.getFirstSelectedOption();

Q. Handling Mouse Action need create an instance of Actions class

By using mouse we can perform the following actions.


 Mouse Hover (Drop Down menu)
 Right Click (Context click )
 Drag and Drop
 Double click

Mouse hover means moving the mouse pointer to a particular location.

Actions actions = new Actions(driver);


actions.click(element).perform(); Click Action
actions.moveToElement(element).perform(); Moving to an Element
actions.doubleClick(element).perform();
actions.contextClick(element).perform(); Right Click element
actions.scrollToElement(element).perform();

WebElement source = driver.findElement(By.id("sourceId"));


WebElement target = driver.findElement(By.id("targetId"));
actions.dragAndDrop(source, target);

Q. TestNG annotations in Selenium


1. @BeforeSuite -: Runs before the entire test suite.
2. @BeforeTest -: Runs before any test method in the <test> tag.
3. @BeforeClass-: Runs before the first method of the current class.
4. @BeforeMethod-: Runs before each test method.
5. @Test-: Marks a method as a test method.
6. @AfterMethod-: Runs after each test method.
7. @AfterClass-: Runs after all the methods in the current class.
8. @AfterTest-: Runs after all the test methods in the <test> tag.
9. @AfterSuite-: Runs after the entire test suite.
10. @DataProvider-: It allows passing multiple sets of data to a test
method. Useful for data-driven testing.
Q. Assertion -:
 Assertion is a feature present in TestNG which is used to verify the
actual and expected result of the test script.
 As per role of automation every expected result should be verify
with assert statement instead of Java if-else statement, because
if-else block does not have capacity to fail the test script.
In assertion there are 2 types-: Assert (Hard Assert) and Soft assert
Assert.assertEquals(); Assert.assertNotEquals();
Assert.assertSame(); Assert.assertNotSame();
Assert.assertNull(); Assert.assertNotNull(tableData);
Assert.assertTrue(false); Assert.assertFalse(false);;
Assert.fail();
Q. Difference Assert and Soft Assert?
Assert
 All the methods are static
 If the comparison fails remaining statements will not be executed in the
current method.
 We do not call AssertAll()
SoftAssert
 All the methods are not-static.
 Executes remaining statements even if comparison fails.
Q. Common Exceptions in Selenium WebDriver:
 NoSuchElementException: Thrown when an element is not
found in the DOM.
 ElementNotVisibleException: Thrown when an element is
present in the DOM but not visible. (DOM- Document Object
Model)
 ElementNotInteractableException: Thrown when an element is
present and visible but not interactable.
 ElementClickInterceptedException: Thrown when an
element that is supposed to be clicked is obscured by another
element.
 TimeoutException: Thrown when a command does not
complete in the given time.
 StaleElementReferenceException: Thrown when a
reference to an element is stale (i.e., the element is no longer
present in the DOM).
 WebDriverException: A general exception that can be thrown
by any WebDriver command.
 InvalidArgumentException: Thrown when an invalid argument
is passed to a method.
Q. Batch Execution & Group Execution:
 Batch execution allows us to run multiple test classes or
methods together in a single run
 This is useful when we want to execute a set of tests as a group,
either sequentially or in parallel
 we can define these batches in a testng.xml file
Group Execution:
 Group execution lets us categorize test methods into different
groups. we can run specific groups of tests based on our needs
 This is particularly useful for separating tests by functionality,
priority, or any other criteria
 Groups can be defined using the @Test annotation with the
groups attribute
Q. How do you handle dynamic elements in Selenium?
 To handle dynamic elements, I use Explicit Waits with
ExpectedConditions to wait for elements to be present, visible,
or clickable.
 I also use CSS selectors or XPath to locate elements based
on partial attributes.
Q. What is the difference between findElement and findElements?
FindElement-:
 Return type of find Element is Web Element.
 Find Element returns a single Web Element,
 Throws a NoSuchElementException if the element is not found.

FindElements-:

 Return type is List< Web Element >


 It return an empty list if no elements are found.
 It will return all the matching elements.
 Used to handle multiple elements.
Q. What is the Page Factory in Selenium?
 It’s a class in Selenium that helps initialize web elements defined in
Page Objects, using @FindBy annotation.
 It improves code readability and makes maintenance easier.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy