Automation QA Testing Course Content

Selenium 4 - Relative Locators

 

Relative Locators

  • Relative locators.
  • Writing and building codes to maintain locators has been a common practice of all test engineers. This practice is quite time-consuming and challenging. 
  • Tools like Sahi and Taiko have features to locate the nearby elements by specifying the directions, however, to accomplish the same in the selenium we need to deal with the complicated xpaths and CSS locators which might result in brittle or flaky test cases.
  • The relative locators in selenium 4 provide a better solution by helping us to locate the elements based on their positions with respect to other elements. 
  • Relative locators provide a newly added locator strategy to the existing eight locator strategies.(id, name, XPath, cssSelector, linkText, partial LinkText, className, and tagName). Relative locators locate the element with respect to the nearby specified elements.
  • A new method withTagName() is added, which returns an instance of RelativeLocator.RelativeBy class, a child class of By and offers methods to specify the direction of an element to be located.
    • above(): Used to locate an element just above the specified element
    • below(): Used to locate an element just below the specified element
    • toLeftOf(): Used to locate an element located on the left side of a specified element
    • toRightOf(): Used to locate an element located on the right side of a specified element
    • near(): By default, it is used to locate an element at 50 pixels distant from a specified element. 

These five relative locators, when added to the existing eight locator strategies, help to get more accurate results for locating the elements, eventually saving from creating flaky test cases.

Note: Method “withTagName()” is added which returns an instance of RelativeLocator. Above relative locators support this method “withTagName()


//Assume element1 is above element2

WebElement element1;

element1 = driver.findElement(By.id("1234"));

String element2 = driver.findElement(withTagName("ABC").below(element1)).getText();

System.out.println("Element below element1 is "+ element2);


//Assume element0 is above element1

WebElement element1;

element1 = driver.findElement(By.id("1234"));

String element0 = driver.findElement(withTagName("ABC").above(element1)).getText();

System.out.println("Element above element1 is "+ element0);



//Assume element1 is on the left side of element3

WebElement element1;

element1 = driver.findElement( withTagName("ABC").toLeftOf(element3)).getText();

System.out.println(" Left of element 3 is : "+ element1);



//Assume element3 is on the right side of element1

WebElement element3;

element3 = driver.findElement( withTagName("ABC").toRightOf(element1)).getText();

System.out.println(" Right of element 1 is : "+ element3);


Latest Selenium Interview Questions and Answers

can you give me limitations of selenium webdriver?

Yes, here are some of the limitations of Selenium WebDriver:



  1. Limited support for testing desktop applications: Selenium WebDriver is primarily designed for testing web applications and has limited support for testing desktop applications.

  2. No built-in reporting mechanism: Selenium WebDriver does not have a built-in reporting mechanism. You'll need to integrate a reporting tool like TestNG or JUnit to get detailed test reports.

  3. No support for image comparison: Selenium WebDriver does not have built-in support for comparing images. You'll need to use external tools to compare images.

  4. Slower test execution: Selenium WebDriver can run tests slower than some other testing tools, particularly for large and complex applications.

  5. Flakiness: Some tests may be unreliable and can produce inconsistent results due to flakiness caused by factors like network connectivity, page loading time, and element timing issues.

  6. Limited support for testing non-HTML content: Selenium WebDriver is designed for testing HTML content and may not work well for non-HTML content such as PDF files or Microsoft Office documents.

  7. Lack of built-in object repository: Selenium WebDriver does not have a built-in object repository, so test code can become cluttered with lengthy locators.

  8. Steep learning curve: Selenium WebDriver can be complex and challenging to learn, especially for users without prior programming experience.

 

can you give some examples where regular expressions are used in java selenium automation testing

Regular expressions can be used in Java Selenium automation testing for various purposes, including:
  1. Verifying page elements: Regular expressions can be used to match patterns in page elements such as text, URLs, or attributes to verify that they match the expected values.

  2. Locating elements: Regular expressions can be used in conjunction with the findElement() method to locate elements that match a specific pattern, such as a specific class name or text.

  3. Extracting data: Regular expressions can be used to extract data from page elements such as text, URLs, or attributes and store them in variables for further use in the automation test.

  4. Validating input: Regular expressions can be used to validate user input, such as email addresses or phone numbers, to ensure that they match a specific pattern.

  5. String manipulation: Regular expressions can be used to perform operations such as searching, replacing, or splitting strings based on a specific pattern.

  6. Here is an example of using regular expressions in Java Selenium to extract the text of an element that matches a specific pattern:





WebElement element = driver.findElement(By.xpath("//*[text()[contains(.,'Search Results')]]"));
String text = element.getText();
Pattern pattern = Pattern.compile("Search Results \\((\\d+)\\)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    int count = Integer.parseInt(matcher.group(1));
    System.out.println("Search Results Count: " + count);
}




...........................................
1)What is difference between selenium 3 and selenium 4 .

  • Selenium 3 uses the JSON wire protocol and selenium 4 use W3C standardisation.
  •  Native Support removed for browsers like Opera and PhantomJs in selenium 4.
  • Selenium IDE was only available as Firefox extension in version 3. However in selenium version 4 IDE is available for Chrome as well.
  • Unlike selenium 3, Selenium 4 provides native support for chrome DevTools.
  • Selenium 4 has introduced Relative locators that allow testers to find elements relative to another element in DOM.
  • Docker support has been added in Grid server for more efficient parallel execution.

2) Which selenium web driver locator should be preferred?

ID is the safest choice which is less prone to change for your app, However CSS is considers to be faster and is usually shorter and cleaner to read. XPath can walk up and down the DOM, which makes Xpath more customizable.

3)Explain difference between findElement() and findElements().

  • findElement(): This command is used for finding a particular element on a web page, it is used to return an object of the first found element by the locator. Throws NoSuchElementException if the element is not found.
  • findElements(): This command is used for finding all the elements in a web page specified by the locator value. The return type of this command is the list of all the matching web elements. It Returns an empty list if no matching element is found.

4)Explain the difference between Thread.Sleep() and selenium.setSpeed().

  • Thread.Sleep() : It causes the current thread to suspend execution for a specified period.
  • selenium.setSpeed():setSpeed sets a speed that will apply a delay time before every Selenium operation.

5)How to handle stale element reference exception ?

The stale element exception occurs when the element is destroyed and recreated again in DOM. When this happens the reference of the element in DOM becomes stale. This can be handled in many ways

6)How many type of WebDriver API’s are available in selenium.

Chrome, Geko Driver, Chromium, Edge.

7)How to open browser in incognito mode.

This can be done by customizing the chromeDriver session using ChromeOptions class and adding argument as “incognito”.

ChromeOptions options = new ChromeOptions();
options.addArguments("--incognito");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);

8)How to handle file upload in selenium.

File upload can be done in 3 ways:

  • By using Robot class.
  • By using sendkeys.
  • By using AutoIt.

9)How many parameters selenium required?

There are four parameters that you have to pass in Selenium are

  • Host
  • Port Number
  • Browser
  • URL

10)How to retrieve css properties of an element.

driver.findElement(By.id(“id“)).getCssValue(“name of css attribute”);
driver.findElement(By.id(“id“)).getCssValue(“font-size”); 

11)How can you use the Recovery Scenario in Selenium WebDriver?

By using “Try Catch Block” within Selenium WebDriver Java tests.

12)How To Highlight Element Using Selenium WebDriver?

JavascriptExecutor js = (JavascriptExecutor) driver;
 js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element); 

13)Explain few advantages of Page Object Model.

  • Readable and Maintainable code.
  • Less and optimised code.
  • Low redundancy.

14)List some Commonly used interfaces of selenium web driver.

  • WebDriver
  • TakesScreenshot
  • JavascriptExecutor
  • WebElement
  • SearchContext

15)What is the difference between @FindAll and @Findbys.



@FindBys :
 When the required WebElement objects need to match all of the given criteria use @FindBys annotation.

@FindBys( {
   @FindBy(className = "class1")
   @FindBy(className = "class2")
} )

private List<WebElement> ele //elements With Both_class1 AND class2;

@FindAll : When required WebElement objects need to match at least one of the given criteria use @FindAll annotation.

@FindAll({
   @FindBy(className = "class1")
   @FindBy(className = "class2")
})
private List<WebElement> ele //elements With Either_class1 OR class2 


16) How to Click on a web element if selenium click() command is not working.

There are multiple ways provided by the selenium web driver to perform click operation. You can use either Action class or can leverage javascript executor.

a) Javascript executor is an interface provided by selenium to run javascript through selenium web driver.


import org.openqa.selenium.JavascriptExecutor;
public void clickThruJS(WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) Driver;
executor.executeScript(“arguments[0].click();”, element);
}

b) Action class is provided by selenium to handle mouse and keyboard interactions. To use the actions class method you need to import it first.

import org.openqa.selenium.interactions.Actions;
public void ClickToElement(WebElement elementName) {
Actions actions = new Actions(Driver);
actions.moveToElement(elementName).perform();
actions.moveToElement(elementName).click().perform();
}

------------------------------------------------------------------------------------------



17) How to exclude a test method from execution in Testng.

By adding the exclude tag in testng.xml file.

<classes> 
 <class name=”TestCaseName”>  
<methods>
<exclude name=”TestMethodName”/>
</methods>
</class>
</classes>


18) What are different ways of ignoring a test from execution.

  • Making parameter “enabled” as “false”.
  • Using “exclude” parameter in testng.xml.
  • “throw new SkipException()” in the if condition to Skip / Ignore Test.


19) What is the difference between scenario and scenario outline in cucumber?

When we want to execute a scenario one time then we use scenario. If we want to execute a scenario multiple times with different sets of data then we use scenario outline. Scenario outline is used for data-driven testing or parametrization. We use example keyword to provide data to the scenario outline.


20) What are different ways to reload webpage in selenium?

1)Driver.navigate().refresh()
2)Driver.get(Driver.getCurrentUrl())
3)Driver. findElement(By.id(“id”)).sendKeys(Keys.F5);
4)Driver.navigate().to(Driver.getCurrentUrl())


21) What is the difference between getText() and getAttribute().

getText() method returns the text present which is visible on the page by ignoring the leading and trailing spaces, while getAttribute() method returns the value of the attribute defined in the HTML tag.


22) How to disable Chrome notifications using selenium?

You need to use chrome options to disable notifications on chrome:

Map<String, Object> prefs = new HashMap<String, Object>();
prefs.put("profile.default_content_setting_values.notifications", 2);
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("prefs", prefs);
WebDriver driver = new ChromeDriver(options);


23) What is the difference between @BeforeTest and @BeforeMethod?

@BeforeTest will run only once before each test tag defined in testng.xml, however, @BeforeMethod will run before every method annotated with the @Test tag. In other words, every test in a file is a method but vice versa is not true, so no matter how many methods are annotated with @Test, @BeforeTest will be called only one time and @BeforeMethod executes before each test method.


24) Explain cucumberOptions with the keywords.

@CucumberOptions enables us to define some settings for our tests, it works like the cucumber JVM command line. Using @CucumberOptions we can define the path of the feature file and the step definition file, we can also use other keywords to set our test execution properly.


25) What is cucumber DryRun?

Dry Run is used to check the complete implementation of all the mentioned steps present in the Feature file. If it is set as true, then Cucumber will check that every Step mentioned in the Feature File has corresponding code written in the Step Definition file or not.


26) Explain Strict and plugin options in cucumber Runner file.

Plugin: plugin Option is used to specify different formatting options for the output reports. Various options that can be used as for-matters are Pretty, HTML, JSON.

Strict: This will cause cucumber to fail unless all the step definitions have been defined if marked as True.


27) How to set the Priority of cucumber Hooks?

@Before(order = int) : This runs in incremental order, like (order=0) will execute first then (order=1) and so on.

@After(order = int): This executes in decremental order, which means value 1 would run first and 0 would be after 1.


28) What is data table in cucumber and how to use it?

Data tables are used when scenario step needs to be tested with numerous input parameters, multiple rows of data can be passed in the same step and it’s much easier to read.

Scenario: Valid Registration Form Information 
Given User submits a valid registration form
| John | Doe |01-01-1990 |999999999 |
Then System proceeds with registration



------------------------------------------------------------------------------------------------------- 29) How to do parameterisation in cucumber feature file?

Example.feature
-----------------
Scenario Outline: Check Validation Errors for Email Field
When Verify Note Created Successfully with "<UserName>"

 Examples: 
|UserName |
| abc   | 


Example.java
------------------
@When("Verify Note Created Successfully with {string}")
public void Verify_Note_Created_Successfully(String type)
{
}


-------------------------------------------------------------------------------------------------------30) Explain invocation count in testng.

  • invocationCount: It refers to the number of times a method should be invoked. It will work as a loop. Eg: @Test(invocationCount = 7) . Hence, this method will execute 7 times
  • ====================================================
31)can you give some examples where regular expressions are used in java selenium automation testing?


-------------------------------------------------------------------------------------------------------Regular expressions can be used in Java Selenium automation testing for various purposes, including:

  1. Verifying page elements: Regular expressions can be used to match patterns in page elements such as text, URLs, or attributes to verify that they match the expected values.

  2. Locating elements: Regular expressions can be used in conjunction with the findElement() method to locate elements that match a specific pattern, such as a specific class name or text.

  3. Extracting data: Regular expressions can be used to extract data from page elements such as text, URLs, or attributes and store them in variables for further use in the automation test.

  4. Validating input: Regular expressions can be used to validate user input, such as email addresses or phone numbers, to ensure that they match a specific pattern.

  5. String manipulation: Regular expressions can be used to perform operations such as searching, replacing, or splitting strings based on a specific pattern.

Here is an example of using regular expressions in Java Selenium to extract the text of an element that matches a specific pattern:


  WebElement element = driver.findElement(By.xpath("//*[text()[contains(.,'Search Results')]]"));
String text = element.getText();
Pattern pattern = Pattern.compile("Search Results \\((\\d+)\\)");
Matcher matcher = pattern.matcher(text);
if (matcher.find()) {
    int count = Integer.parseInt(matcher.group(1));
    System.out.println("Search Results Count: " + count);
}




In this example, the text of the element is extracted and a regular expression is used to match the pattern "Search Results (\d+)" to extract the number of search results. The extracted count is then printed to the console.