190+ Most Popular Advanced Selenium Interview Questions And Answers
Are you preparing for a Selenium interview? If so, you’ll want to be sure to brush up on your Selenium interview questions.
In this blog post, we’ll provide you with a list of Selenium interview questions that are likely to come up in an interview setting. We’ll also provide tips on how to answer these questions.
Basic & Advanced Selenium WebDriver Interview Questions
No matter you are experienced or freshers, we have covered all levels based on the requests we got from our readers. Here we have covered Selenium Interview Questions asked in companies.
Here are some hand-picked posts you must read after the below 100+ Selenium Interview Questions and Answers.
- Explain Selenium Test Automation Framework
- Selenium Framework Interview Questions
- Selenium Java Interview Questions For Selenium Automation Testers
- Selenium Python Interview Questions For Selenium Testers
- Test Automation Framework Interview Questions
- Selenium Automation Interview Questions
- TestNG Interview Questions
- Why you chose Software Testing As Your Career
- Manual Testing Interview Questions
- Cypress Interview Questions
- Agile Interview Questions
- SQL Interview Questions
1. What is Automation Testing?
Automation testing is the process of testing a software or application using an automation testing tool to find the defects. In this process, executing the test scripts and generating the results are performed automatically by automation tools. It is required when we have a huge amount of regression test cases. Some most popular tools to do automation testing are HP QTP/UFT, Selenium WebDriver, etc.,
2. What are the benefits of Automation Testing?
This is one of the common interview questions in any Automation testing job.
- Saves time and money. Automation testing is faster in execution.
- Reusability of code. Create one time and execute multiple times with less or no maintenance.
- Easy reporting. It generates automatic reports after test execution.
- Easy for compatibility testing. It enables parallel execution in the combination of different OS and browser environments.
- Low-cost maintenance. It is cheaper compared to manual testing in a long run.
- Automated testing is more reliable.
- Automated testing is more powerful and versatile. Automation tools allow us to integrate with Cross Browser Testing Tools, Jenkins, Github, etc.,
- It is mostly used for regression testing. Supports execution of repeated test cases.
- Minimal manual intervention. Test scripts can be run unattended.
- Maximum coverage. It helps to increase the test coverage.
3. What are the challenges and limitations of Selenium WebDriver?
As we all know Selenium WebDriver is a tool that automates the browser to mimic real user actions on the web. Selenium is a free open source testing tool. Some of the challenges with Selenium WebDriver are as follows
- We cannot test the windows application
- We cannot test mobile apps
- Limited reporting
- Handling dynamic Elements
- Handling page load
- Handling pop up windows
- Handling captcha
Read the detailed explanation on the challenges and limitations of Selenium WebDriver
4. What type of tests have you automated?
Our main focus is to automate test cases to do Regression testing, Smoke & Sanity testing. Sometimes based on the project and the test time estimation, we do focus on End to End testing.
5. How many test cases you have automated per day?
It is one of the Selenium Tricky Interview Questions.
Actually, it depends on Test case scenario complexity and length. I did automate 2-5 test scenarios per day when the complexity is limited. Sometimes just 1 or fewer test scenarios in a day when the complexity is high.
6. What is a Framework?
A framework defines a set of rules or best practices that we can follow in a systematic way to achieve the desired results. There are different types of automation frameworks and the most common ones are:
- Data-Driven Testing Framework
- Keyword Driven Testing Framework
- Hybrid Testing Framework
- Behavioural Driven Framework
Detailed Explanation: Types of Framework
7. What type of test cases to be automated?
Types of Test Cases To Automate are
- Data-driven test cases
- Test cases with higher complexity
- Test case with many database updates
- The test execution rate is high
- Smoke/Critical tests
- Tests with several combinations
- Graph test cases
- Higher manual execution time
Read in detail explanation on types of test cases to be automated here
8. What type of test cases not to be automated?
Types of Test Cases Not To Be Automated are
- Subjective Validation
- New Functionalities
- Strategic Development
- User Experience
- Complex Functionality
- Quality Control
- Low return on investment
- Installation and setup testing
Read in detail explanation on types of test cases not to be automated here
9. What are the advantages of the Test Automation Framework?
- Reusability of code.
- Easy reporting.
- Low-cost maintenance.
- Maximum Coverage
- Minimal manual intervention
10. Have you created any Framework?
If you are a beginner: You can say “No, I didn’t get a chance to create a framework from the scratch. I have used the framework which is already available. My contribution is mostly in creating test cases by using the existing framework.”
If you are a beginner but have good knowledge of creating framework: You can say “Yes, I have involved in developing framework along with other automation testers in my company.”
If you are an experienced tester: You can say “I have contributed to developing framework.” or You can say “Yes, I have created a framework from the scratch. There was no automation process in my previous company. I designed the framework from the scratch.”
11. How would you explain the Selenium test automation framework in the interview?
Here we have clearly explained each component of the Framework. Check this post to learn more about how to explain the selenium test automation framework to the interviewer.
12. Why do you prefer Selenium Automation Tool?
I prefer Selenium Automation Tool because some of the benefits of Selenium to do automation testing are
- Free and open source – It is a free open source tool. There is no need to allot budget for this tool
- Help – Have large user base and helping communities.
- Cross-browser compatibility – It works on almost all popular browsers such as Chrome, Firefox, Internet Explorer, and Safari.
- Cross Platform compatibility – It works on platforms such as Windows, Linux, Mac.
- Multiple programming languages – It supports programming languages such as Java, Phyton, Perl, Php, C#, Ruby, etc.,
- Parallel Execution – Selenium Grid supports parallel execution of Selenium Scripts.
- Continuous Integration – We can achieve nightly execution using Jenkins.
13. What is Selenium?
Selenium is an open source (free) automated testing suite to test web applications. It supports different platforms and browsers. It has gained a lot of popularity in terms of web-based automated testing and giving a great competition to the famous commercial tool HP QTP (Quick Test Professional) AKA HP UFT (Unified Functional Testing).
Selenium is a set of different software tools. Each tool has a different approach in supporting web based automation testing.
It has four components namely,
- Selenium IDE (Selenium Integrated Development Environment)
- Selenium RC (Selenium Remote Control)
- Selenium WebDriver
- Selenium Grid
14. What is Selenium IDE?
Selenium IDE (Integrated Development Environment) is a Firefox plugin. It is the simplest framework in the Selenium Suite. It allows us to record and playback the scripts. Even though we can create scripts using Selenium IDE, we need to use Selenium RC or Selenium WebDriver to write more advanced and robust test cases.
15. What is Selenese?
Selenese is the language that is used to write test scripts in Selenium IDE.
16. Which is the only browser that supports Selenium IDE to be used?
Firefox and Chrome. However, as Selenium IDE is community-powered, regular updates and compatibility with new browser versions cannot be ensured.
Back in 2017 when it no longer worked with Firefox’s latest version, users switched to Katalon Recorder. It supports the same commands, extension scripts, data-driven testing, and advanced test reporting platform with TestOps.
17. What is Selenium RC?
Selenium RC AKA Selenium Remote control / Selenium 1. Selenium Remote Control was the main Selenium project for a long time before the WebDriver merge brought up Selenium 2. Selenium 1 is still actively supported (in maintenance mode). It relies on JavaScript for automation. It supports Java, Javascript, Ruby, PHP, Python, Perl, and C#. It supports almost every browser out there.
18. What is Selenium WebDriver?
Selenium WebDriver AKA Selenium 2 is a browser automation framework that accepts commands and sends them to a browser. It is implemented through a browser-specific driver. It controls the browser by directly communicating with it. Selenium WebDriver supports Java, C#, PHP, Python, Perl, Ruby.
Learn Selenium WebDriver Architecture
19. What is the difference between Selenium 3 and Selenium 4?
We all know that Selenium 4 was released as a stable version on October 13, 2021. So here in this post, we have covered Selenium 4 Interview Questions & Answers. First Let’s see the difference between Selenium 3 and Selenium 4.
Selenium 3 – JSON wire protocol was used to communicate between the Selenium Webdriver APIs and the browser native APIs. All the requests and responses communicated across the protocol were encoded & decoded.
Selenium 4 – Follows the W3C standard protocol. Due to this request and the response communicated across the protocol doesn’t require the encoding and decoding API. Selenium 4 is the latest version of Selenium. With this, we can create more stable selenium test suites and can reduce compatibility issues across different web browsers.
Checkout new features of Selenium 4
20. What are some features of Selenium 4?
Some of the new features of Selenium 4 are
- It is W3C compliant, ensuring more stable cross-browser tests.
- The Selenium Grid feature is now more user-friendly and includes support for Docker, which uses OS-level virtualization to deliver software in containers.
- Introduced Relative locators (aka Friendly locators), allow us to locate the WebElements by its position by concerning other web elements such as above, below, toLeftOf, toRightOf, and near.
- With Selenium 4, it’s possible to manage multiple tabs or windows within the same session. You can open a new tab or window without needing to create a new driver object.
- Native support for Opera and PhantomJS has been discontinued due to the cessation of active development for their WebDriver implementations.
- Selenium 4 introduces a new IDE for both Chrome and Firefox.
- The new Selenium 4 IDE allows tests to be exported to various programming languages such as Java, JavaScript, C# etc.,
- Selenium 4 offers more detailed and improved documentation.
21. What is Selenium Grid?
Selenium Grid is a tool used together with Selenium RC to run tests on different machines against different browsers in parallel. That is, running multiple tests at the same time against different machines running different browsers and operating systems.
In simple words, it is used to distribute your test execution on multiple platforms and environments concurrently.
22. When do you use Selenium Grid?
Selenium Grid can be used to execute same or different test scripts on multiple platforms and browsers concurrently so as to achieve distributed test execution
23. What are the advantages of Selenium Grid?
It allows running test cases in parallel thereby saving test execution time.
It allows multi-browser testing
It allows us to execute test cases on multi-platform
24. What is a hub in Selenium Grid?
A hub is a server or a central point that controls the test executions on different machines.
25. What is a node in Selenium Grid?
Node is the machine which is attached to the hub. There can be multiple nodes in Selenium Grid.
26. What are the types of WebDriver APIs available in Selenium?
- Firefox Driver
- Gecko Driver
- InternetExplorer Driver
- Chrome Driver
- HTMLUnit Driver
- Opera Driver
- Safari Driver
- Android Driver
- iPhone Driver
- EventFiringWebDriver
27. Which WebDriver implementation claims to be the fastest?
The fastest implementation of WebDriver is the HTMLUnitDriver. It is because the HTMLUnitDriver does not execute tests in the browser. Starting a browser and running test cases took more time compared to running the scripts without a browser. HTMLUnitDriver took a simple HTTP request-response mechanism for test case execution.
Learn more on How To Do Headless Browser Testing using Selenium WebDriver
28. What are the Programming Languages supported by Selenium WebDiver?
- Java
- C#
- Python
- Ruby
- Perl
- PHP
29. Which language is not supported by selenium?
Selenium supports all major programming languages such as Java, C#, Perl, Python, Ruby, PHP, Scala and Groovy. As of today, others are not compatible.
30. What are the Operating Systems supported by Selenium WebDriver?
- Windows
- Linux
- Mac OS X
- iOS
- Android
31. What are the testing types that can be supported by selenium?
Testing types that can be supported by Selenium are as follows:
- Functional Testing
- Regression Testing
- Retesting
- Acceptance Testing
- End-to-End Testing
- Smoke Testing
- Sanity Testing
- Responsive Testing
- Cross Browser Testing
- UI Testing
- Integration Testing
32. What is a data-driven framework?
A data-driven framework is a methodology in test automation where test data is separated from the test scripts. This allows for more flexibility and scalability in testing. In this framework, the same test scripts can run with multiple sets of data, enabling comprehensive coverage and robustness of the tests. The test data is usually stored in external files such as Excel sheets, CSV files, or databases. By doing so, testers can easily manage, update, and manipulate test data without having to alter the actual test scripts. This approach not only saves time but also enhances the maintainability and readability of test automation projects.
33. What is a keyword-driven framework?
A keyword-driven framework is an advanced methodology in test automation where the focus is on defining keywords for each function or action to be performed. Each keyword corresponds to a specific operation such as clicking a button, navigating to a webpage, or verifying a result. These keywords are maintained in a separate file, often in a tabular format such as Excel or a database, which drives the execution of the test scripts. This approach allows testers to write tests without deep knowledge of the underlying code, making it accessible to both technical and non-technical team members. By abstracting the implementation details, a keyword-driven framework enhances reusability, maintainability, and overall clarity of the automation tests.
Examples:
To launch a browser, the keyword we use is – lauchBrowser()
To enter data in a text box, the keyword we use is – writeInTextBox(webElement, textToWrite)
34. What is a hybrid framework?
A hybrid framework in test automation is a sophisticated blend of multiple frameworks, combining the strengths of data-driven, keyword-driven, and sometimes modular frameworks. The main goal of a hybrid framework is to leverage the advantages of each integrated framework to maximize the effectiveness, flexibility, and maintainability of the test automation process. For instance, a hybrid framework can utilize the data management capabilities of a data-driven approach while taking advantage of the high abstraction level of a keyword-driven framework. This allows testers to use keywords to define actions and scenarios, while also enabling the reuse of these keywords across multiple data sets for broader test coverage. The hybrid nature empowers teams to tailor the framework to suit their specific needs, adapting to various types of applications and testing scenarios. Consequently, this approach results in a robust, scalable, and high-performance test automation solution.
35. How many parameters can selenium commands have at minimum?
There are four parameters that you have to pass in Selenium are
- Host
- Port Number
- Browser
- URL
Host: It is the parameter which we use to bind Selenium to a specific IP. Usually, we run selenium tests on our local machine so the value will be ‘localhost’. You can sepcify IP address instead of localhost.
java -jar <selenium server standalone jar name> -host <Your IP Address>
Port Number: TCP/IP port which is used to connect selenium tests to the selenium grid hub. Default port hub is 4444.
java -jar <selenium server standalone jar name> -role hub -port 4444
Make sure no other application in your system is using this port. You may face an exception like Exception in thread “main” java.net.BindException: Selenium is already running on port 4444. Or some other service is.
If this occurs you can either shutdown the other process that is using port 4444, or you can tell Selenium-Grid to use a different port for its hub. Use the -port option for changing the port used by the hub.
java -jar <selenium server standalone jar name> -role hub -port 4441
Browser: To pass the browser which has to execute our selenium scripts
URL: To pass the application URL
36. What are the Open-source Frameworks supported by Selenium WebDriver?
- JUnit
- TestNG
Read: TestNG Complete Tutorial
37. What are the Locators available in Selenium?
In Selenium WebDriver, there are 8 different types of locators:
- ID – Practical example
- ClassName – Practical example
- Name – Practical example
- TagName – Practical example
- LinkText – Practical example
- PartialLinkText – Practical example
- XPath – Practical example
- CSS Selector – Practical example
Click here to see the detailed post on Locators.
38. What is an XPath?
XPath is used to locate the elements. Using XPath, we could navigate through elements and attributes in an XML document to locate web elements such as textbox, button, checkbox, Image etc., in a web page.
Learn How To Write Dynamic XPath
39. When you use these locators ID, Name, XPath, Or CSS Selector?
ID & Name locators will be used when there are unique identifiers & unique names available on the web page.
CSS Selector can be used for performance and when ID & Name locators are not unique.
XPath is used when there is no preferred locators.
40. What is the difference between “/” and “//”
Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node.
Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document.
41. What is the difference between Absolute Path and Relative Path?
Absolute XPath starts from the root node and ends with desired descendant element’s node. It starts with top HTML node and ends with input node. It starts with a single forward slash(/) as shown below.
/html/body/div[3]/div[1]/form/table/tbody/tr[1]/td/input
Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the element). It starts with a double forward slash(//) as shown below.
//input[@id='email']
42. How are dynamic web elements handled using Selenium?
Handling dynamic web elements in Selenium involves several methods to ensure robust and reliable test automation. Techniques such as explicit waits, which pause the execution until a specific condition is met, are crucial. Additionally, the use of dynamic locators, like XPath and CSS selectors, allows for the identification of elements that change based on certain criteria. You can use these strategies to ensure that tests can adapt to the ever-changing nature of web applications, maintaining accuracy and efficiency.
43. How can we inspect web element attributes to use them in various locators?
To locate web elements, we can utilize the Developer tool. The developer tool can be launched by pressing F12 on the browser. Users can then hover over any element to reveal its various HTML properties.
44. How can we move to an element’s parent using XPath?
By appending ‘/..’ to the XPath expression of a child element, we can move to its parent element.
For example, the locator //div[@id=”child-Id”]/.. will move to the parent of the `div` element with the `id` value ‘child-Id’.
45. How can we move to the nth-child element using XPath?
There are two ways of navigating to the nth element using XPath-
- Using square brackets with index position
Example: div[4] will find the fourth div element. - Using position()
Example: div[position()=2] will find the second div element.
46. How do you use a CSS Selector to find elements by class?
Using .className in CSS locators allows us to select all the elements that belong to a specific class. For example, ‘.student’ will select all elements with the class ‘student’.
47. How do you use a CSS Selector to find elements by id?
Using #idValue in CSS locator allows us to select all the elements that belong to a specific id e.g. ‘#studentId’ will select the element having an id ‘studentId’.
48. How can we use CSS Selectors to target elements based on their attribute values?
By using [attribute=value] in a CSS selector, we can target all elements with a specific attribute. For instance, ‘[type=id]’ will select any element where the ‘type’ attribute has the value ‘id’.
49. How can we select the nth-child element using a CSS selector?
Using :nth-child(n) in CSS, you can target the nth child element. For example, div:nth-child(3) will select the thirddiv element within its parent.
50. What are the difference between XPath and CSS selectors?
Feature | XPath Selector | CSS Selector |
---|---|---|
Traversal Direction | Bidirectional: Can traverse elements from parent to child or child to parent | Unidirectional: Can only traverse from parent to child |
Performance | Slower in terms of speed and performance | Comparatively faster |
Readability | Less readable as it grows | More readable |
Text-based Selector Construction | Allows the construction of text-based selectors | Does not allow the construction of text-based selectors |
Syntax Start | Starts with / or // followed by a tag name or wildcards like * | Directly allows some attribute-based selectors such as # for ID and . for classes |
Axes Methods | Provides Axes to solve complicated selector problems | Does not have Axes methods |
Complex Queries | Can perform complex queries like selecting elements based on their position or content | Limited to selecting elements based on their class, ID, or other attributes |
Attribute Selection | Can select elements based on a wider range of attributes and conditions | Limited to fewer attribute types |
Browser Compatibility | Supported by most browsers but may have inconsistencies | Widely supported and consistent across modern browsers |
Use Cases | Useful for detailed and specific selections, such as automated testing scripts | Ideal for simpler and more general styling tasks like CSS styling and JavaScript interactions |
51. What should you do when even XPath functions can’t identify the web element?
In the early stages of software developement, developers change identifiers and elements quite often. During the execution, the web elements may change dynamically and we cannot identify the web elements. To overcome this we use XPath axes along with XPath functions.
52. What are XPath Axes?
XPath axes are used to search for the multiple nodes in the XML document from the context (current) node.
XPath axes are used to find dynamic elements that would otherwise be impossible using standard locators.
53. What is a Context Node?
A context Node in Selenium refers to a node in the Document Object Model (DOM) that serves as the reference point for locating or interacting with web elements. In Selenium WebDriver, the context node is crucial when using methods like `findElement` or `findElements`, where you specify a starting point in the DOM hierarchy for searching elements. For instance, you can set a context node to narrow down the search scope to specific sections of a webpage, improving efficiency and accuracy in locating elements. This becomes particularly useful when dealing with complex web pages with nested elements and helps avoid conflicts or misidentifications. By understanding and leveraging context nodes, testers can create more robust and maintainable test scripts.
54. What is the difference between Assert and Verify in Selenium?
Assert: In simple words, if the assert condition is true then the program control will execute the next test step but if the condition is false, the execution will stop and further test step will not be executed.
Verify: In simple words, there won’t be any halt in the test execution even though the verify condition is true or false.
Read this detailed post on Assert vs Verify with practical example here detailed post check the below link.
55. What are Soft Assert and Hard Assert in Selenium?
Soft Assert: Soft Assert collects errors during @Test
Soft Assert does not throw an exception when an assert fails and would continue with the next step after the assert statement.
Hard Assert: Hard Assert throws an AssertException immediately when an assert statement fails and test suite continues with next @Test
Detailed Post: Soft Assert
56. What is the difference between setSpeed () and sleep () methods?
Both sleep() and setSpeed() are used to delay the execution speed.
setSpeed(): It set up speed that will apply a delay time before every Selenium operation.
Example: setSpeed(“5000”) – It waits for 5 seconds
sleep(): It set up wait only for once when called in our Selenium script.
Example: sleep(5000) – It waits for 5 seconds
Note: setSpeed method is applicable to Selenium IDE and Selenium RC. We cannot use setSpeed in Selenium WebDriver.
57. What are the verification points available in Selenium?
In Selenium IDE, we use Selenese Verify and Assert Commands as Verification points
In Selenium WebDriver, there is no built-in features for verification points. It totally depends on our coding style. some of the Verification points are
- To check for page title
- To check for certain text
- To check for certain element (text box, button, drop down, etc.)
58. How to launch a browser using Selenium WebDriver?
WebDriver is an Interface. We create an Object of a required driver class such as FirefoxDriver, ChromeDriver, InternetExplorerDriver etc.,
To launch Firefox Driver:
WebDriver driver = new FirefoxDriver();
Note: If you use geckodriver with Selenium, you must upgrade to Selenium 3.3. Here we have to set the property as follows
System.setProperty("webdriver.gecko.driver", "D:\\Selenium Environment\\Drivers\\geckodriver.exe");
To launch Chrome Driver:
WebDriver driver = new ChromeDriver();
To launch Internet Explorer Driver:
WebDriver driver = new InternetExplorerDriver();
To launch Safari Driver:
WebDriver driver = new SafariDriver();
59. Is the FirefoxDriver a Class or an Interface?
FirefoxDriver is a Java class, and it implements the WebDriver interface.
60 What is the super interface of WebDriver?
SearchContext acts as the super interface of Web Driver.
61. Explain the line of code Webdriver driver = new FirefoxDriver(); ?
Webdriver driver = new FirefoxDriver();
‘WebDriver‘ is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.
Read more on why WebDriver driver = new FirefoxDriver();
62. We do create a reference variable ‘driver’ of type WebDriver as shown below. What is the purpose of doing this way?
WebDriver driver = new FirefoxDriver();instead of creatingFirefoxDriver driver = new FirefoxDriver();
If we create a reference variable driver of type WebDriver then we could use the same driver variable to work with any browser of our choice such as IEDriver, SafariDriver etc.,
63. What is WebElement selenium?
WebElement in Selenium represents an HTML element. It basically represents a DOM element in a HTML document.
64. What are the different exceptions you have faced in Selenium WebDriver?
Some of the exceptions I have faced in my current project are
- ElementNotVisibleException
- StaleElementReferenceException
Element Not visible Exception:
This exception will be thrown when you are trying to locate a particular element on webpage that is not currently visible eventhough it is present in the DOM. Also sometimes, if you are trying to locate an element with the xpath which associates with two or more element.
Stale Element Reference Exception:
A stale element reference exception is thrown in one of two cases, the first being more common than the second.
The two reasons for Stale element reference are
- The element has been deleted entirely.
- The element is no longer attached to the DOM.
We face this stale element reference exception when the element we are interacting is destroyed and then recreated again. When this happens the reference of the element in the DOM becomes stale. Hence we are not able to get the reference to the element.
Some other exceptions we usually face are as follows:
- WebDriverException
- IllegalStateException
- TimeoutException
- NoAlertPresentException
- NoSuchWindowException
- NoSuchElementException
65. How to handle STALEELEMENTREFERENCEEXCEPTION?
Before looking how to handle Stale Element Reference Exception through Page Object Model. Let’s see what is Stale Element Reference Exception first.
Stale means old, decayed, no longer fresh. Stale Element means an old element or no longer available element. Assume there is an element that is found on a web page referenced as a WebElement in WebDriver. If the DOM changes then the WebElement goes stale. If we try to interact with an element which is staled then the StaleElementReferenceException is thrown.
Here we have given solutions to handle StaleElementReferenceException in detail.
66. What are the types of waits available in Selenium WebDriver?
In Selenium we could see three types of waits such as Implicit Waits, Explicit Waits and Fluent Waits.
- Implicit Waits – Click to view detailed post
- Explicit Waits – Click to view detailed post
- Fluent Waits – Click to view detailed post
67. What is Implicit Wait In Selenium WebDriver?
Implicit waits tell to the WebDriver to wait for a certain amount of time before it throws an exception. Once we set the time, WebDriver will wait for the element based on the time we set before it throws an exception. The default setting is 0 (zero). We need to set some wait time to make WebDriver to wait for the required time.
68. What is WebDriver Wait In Selenium WebDriver?
WebDriverWait is applied on a certain element with defined expected condition and time. This wait is only applied to the specified element. This wait can also throw an exception when an element is not found.
69. What is Fluent Wait In Selenium WebDriver?
FluentWait can define the maximum amount of time to wait for a specific condition and frequency with which to check the condition before throwing an “ElementNotVisibleException” exception.
70. What happen if you mix both implicit wait and explicit wait in a Selenium Script?
As per the official Selenium documentation, it is suggested not to mix both Implicit waits and Explicit Waits. Mixing both of them can cause unpredictable wait times.
Implicit wait is defined only once in the code. It will remain same throughout the driver object instance.
Explicit wait is defined whenever it is necessary in the code. This wait will call at the time of execution. It is a conditional wait.
Explicit wait will overwrite the implicit wait where ever explicit wait is applied. So, Explicit Wait gets first preference then Implicit Wait.
71. What happen if you mix both Thread.Sleep and WebDriver Waits in a Selenium Script?
Thread.sleep() method can be used to pause the execution for specified time in milliseconds
If we use WebDriver waits along with Thread.sleep() method then webdriver will hold the execution for specified time and then will follow other wait. Test execution time will become more, if we mix both waits.
72. How to Login into any site if it is showing an Authentication Pop-Up for Username and Password?
To do this we pass username and password with the URL
http://username:password@url e.g. http://myUserName:myPassword@softwaretestingmaterial.com
73. How to input text in the text box using Selenium WebDriver?
By using sendKeys() method
WebDriver driver = new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.findElement(By.xpath("xpath")).sendKeys("Software Testing Material Website");
74. How to input text in the text box without calling the sendKeys()?
// To initialize js object JavascriptExecutor JS = (JavascriptExecutor)webdriver; // To enter username JS.executeScript("document.getElementById('User').value='SoftwareTestingMaterial.com'"); // To enter password JS.executeScript("document.getElementById('Pass').value='tester'");
75. How to clear the text in the text box using Selenium WebDriver?
By using clear() method
WebDriver driver = new FirefoxDriver(); driver.get("https://www.gmail.com"); driver.findElement(By.xpath("xpath_of_element1")).sendKeys("Software Testing Material Website"); driver.findElement(By.xpath("xpath_of_element1")).clear();
76. How to get a text of a web element?
By using getText() method
package softwareTestingMaterial; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Test; public class TestTestTest { @Test public void testmethod(){ System.setProperty("webdriver.chrome.driver", "D:\\Selenium Environment\\Drivers\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://www.google.com"); String availableText = driver.findElement(By.xpath("//*[@id='gbw']/div/div/div[1]/div[1]/a")).getText(); System.out.println("Text Available is :"+availableText); } }
77. How to get an attribute value using Selenium WebDriver?
By using getAttribute(value);
It returns the value of the attribute passed as a parameter.
HTML:
<input name="nameSelenium" value="valueSelenium">SoftwareTestingMaterial</input>
Selenium Code:
String attributeValue = driver.findElement(By.name("nameSelenium")).getAttribute("value"); System.out.println("Available attribute value is :"+attributeValue); Output: valueSelenium
78. How to click on a hyperlink using Selenium WebDriver?
We use click() method in Selenium to click on the hyperlink
driver.findElement(By.linkText(“Software Testing Material Website”)).click();
79. How to submit a form using Selenium WebDriver?
We use “submit” method on element to submit a form
driver.findElement(By.id("form_1")).submit();
Alternatively, you can use click method on the element which does form submission
80. How to press ENTER key on text box In Selenium WebDriver?
To press ENTER key using Selenium WebDriver, We need to use Selenium Enum Keys with its constant ENTER.
driver.findElement(By.xpath("xpath")).sendKeys(Keys.ENTER);
81. How to pause a test execution for 5 seconds at a specific point?
By using java.lang.Thread.sleep(long milliseconds) method we could pause the execution for a specific time. To pause 5 seconds, we need to pass parameter as 5000 (5 seconds)
Thread.sleep(5000)
82. Is Selenium Server needed to run Selenium WebDriver Scripts?
When we are distributing our Selenium WebDriver scripts to execute using Selenium Grid, we need to use Selenium Server.
83. What happens if I run this command. driver.get(“www.softwaretestingmaterial.com”) ;
If the URL doesn’t contain http or https prefix then an exception is thrown. So, we need to pass HTTP protocol within driver.get() method.
driver.get("https://www.softwaretestingmaterial.com");
84. What is the alternative to driver.get() method to open an URL using Selenium WebDriver?
Alternative method to driver.get(“url”) method is driver.navigate.to(“url”)
85. What is the difference between driver.get() and driver.navigate.to(“url”)?
driver.get(): To open an URL and it will wait till the whole page gets loaded
driver.navigate.to(): To navigate to an URL and It will not wait till the whole page gets loaded
86. Can I navigate back and forth in a browser in Selenium WebDriver?
We use Navigate interface to do navigate back and forth in a browser. It has methods to move back, forward as well as to refresh a page.
driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history
driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history
driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements
driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL
87. What are the different types of navigation commands?
Refer above question (Can I navigate back and forth in a browser)
88. How to fetch the current page URL in Selenium?
To fetch the current page URL, we use getCurrentURL()
driver.getCurrentUrl();
89. How can we maximize browser window in Selenium?
To maximize browser window in selenium we use maximize() method. This method maximizes the current window if it is not already maximized
driver.manage().window().maximize();
90. How to delete cookies in Selenium?
To delete cookies we use deleteAllCookies() method
driver.manage().deleteAllCookies();
91. What are the ways to refresh a browser using Selenium WebDriver?
There are multiple ways to refresh a page in selenium
- Using driver.navigate().refresh() command as mentioned in the question 45
- Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
- Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
- Using sendKeys(Keys.F5) on any textbox on the webpage
92. What is the difference between driver.getWindowHandle() and driver.getWindowHandles() in Selenium WebDriver?
driver.getWindowHandle() – It returns a handle of the current page (a unique identifier)
driver.getWindowHandles() – It returns a set of handles of the all the pages available.
93. What is the difference between driver.close() and driver.quit() methods?
Purpose of these two methods (driver.close and driver.quit) is almost same. Both allow us to close a browser but still, there is a difference.
driver.close(): To close current WebDriver instance
driver.quit(): To close all the opened WebDriver instances
94. What is the difference between driver.findElement() and driver.findElements() commands?
The difference between driver.findElement() and driver.findElements() commands is-
- findElement() returns a single WebElement (found first) based on the locator passed as parameter. Whereas findElements() returns a list of WebElements, all satisfying the locator value passed.
- Syntax of findElement()-
WebElement textbox = driver.findElement(By.id(“textBoxLocator”));
Syntax of findElements()-
List <WebElement> elements = element.findElements(By.id(“value”)); - Another difference between the two is- if no element is found then findElement() throws NoSuchElementException whereas findElements() returns a list of 0 elements.
95. What Is The Difference Between MaxSessions Vs. MaxInstances Properties in Selenium Grid?
MaxInstances is the no. of browser instances of the same version of the browser that can run on the remote machine.
Let’s see an example below:
-browser browserName=InternetExplorer,version=6,maxInstances=2,platform=WINDOWS -browser browserName=firefox,version=11,maxInstances=2,platform=WINDOWS
As per the above example, it will allow us to run 4 instances of both IE and Firefox at the same time (in parallel) in a remote machine.
MaxSession says how many browsers, independent of the type & version, can run in parallel on the remote machine.
It supersedes the “MaxInstances” setting.
If maxSession=1 then no more than a single browser would run. If maxSession=2 then any of the below combinations can run at a time irrespective of what MaxInstances we have defined.
2 Internet Explorer
2 Firefox
1 Internet Explorer + 1 Firefox
96. How to find whether an element is displayed on the web page?
WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.
- isDisplayed()
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
- isSelected()
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected();
- isEnabled()
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();
97. How to select a value in a dropdown?
By using Select class
WebElement mySelectElement = driver.findElement(By.name("dropdown")); Select dropdown = new Select(mySelectElement); dropdown.selectByVisibleText(Text); dropdown.selectByIndex(Index); dropdown.selectByValue(Value);
98. How to capture Screenshot in Selenium WebDriver?
Test cases may fail while executing the test scripts. While we are executing the test cases manually we just take a screenshot and place in a result repository. The same can be done by using Selenium WebDriver.
Some of the scenarios we may need to capture a screenshot using Selenium WebDriver are
i. Application issues
ii. Assertion Failure
iii. Difficulty to find Webelements on the web page
iv. Timeout to find Webelements on the web page
Selenium provides an interface called TakesScreenshot which has a method getScreenShotAs which can be used to take a screenshot of the application under test.
In Selenium 3, we may face few issues while capturing Screenshots. To overcome we use aShot utility. Click on below links to see posts related to the normal way of capturing a screenshot and capturing a screenshot using aShot utility.
- Capture screenshot using Selenium WebDriver
- Full Page Screenshot using aShot utility
- Failed Test Cases Screenshot
99. How to mouse hover on a web element using WebDriver?
By using Actions class
WebElement ele = driver.findElement(By.xpath("xpath")); //Create object 'action' of an Actions class Actions action = new Actions(driver); //Mouseover on an element action.moveToElement(ele).perform();
100. How can we handle Web-based Pop-ups or Alerts in Selenium?
To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.
dismiss(): To click on Cancel button.
accept(): To Click on OK button.
getText(): To get the text which is present on the Alert.
sendKeys(): To enter the text into the alert box.
101. How can we handle windows based pop up?
Selenium doesn’t support windows based applications. It is an automation testing tool which supports only web application testing. We could handle windows based popups in Selenium using some third party tools such as AutoIT, Robot class etc.
102. What is Robot API?
Robot API is used for handling Keyboard and Mouse events.
Robot robot = new Robot(); //Simulate enter key action robot.keyPress(KeyEvent.VK_ENTER);
103. Which API can be used for reading and writing data to Excel files.
The Apache POI API and JXL (Java Excel API) are tools that enable reading, writing, and updating of Excel files.
104. Which API can be used for logging in Java.
Log4j is a widely used open-source API for logging in Java, offering multiple logging levels: ALL, DEBUG, INFO, WARN, ERROR, TRACE, and FATAL.
105. What is the use of logging in automation?
Logging assists in debugging tests when necessary and offers a storage of the test’s runtime behavior.
106. What is the purpose of the testng.xml file?
A testng.xml file is used to configure and trigger the test suite. Within this file, we can create a test suite, test groups, tests for parallel execution, add listeners, and pass parameters to test scripts.
Selenium Coding Interview Questions And Answers
107. How can we pass the parameter to the test script using TestNG?
Using @Parameter annotation and the ‘parameter’ tag in testng.xml, we can seamlessly pass parameters to the test script.
Sample testng.xml
<suite name="sampleTestSuite">
<test name="sampleTest">
<parameter name="sampleParamName" value="sampleValue"/>
<classes>
<class name="TestFile" />
</classes>
</test>
</suite>
Sample test script
public class TestFile {
@Test
@Parameters("sampleParamName")
public void parameterTest(String paramValue) {
System.out.println("Value of sampleParamName is " + sampleParamName);
}
108. How can we make one test method dependent on others using TestNG?
By utilizing the ‘dependsOnMethods’ parameter within the @Test annotation in TestNG, we can ensure that a test method executes only after the successful completion of its dependent test method.
@Test(dependsOnMethods = { "preTests" })
109. What is the default priority assigned to a test method in TestNG?
When not specified, a test’s default priority is set to an integer value of 0. Therefore, if one test case has a priority of 1 and another has no specified priority, the test without an assigned priority will execute first.
110. How can you prevent a test case from executing in TestNG?
To prevent a test method from executing, set the “enabled” attribute to false.
//In case of a test method
@Test(enabled = false)
public void testMethodA() {
//write your test logic here
}
//In case of test method belonging to a group
@Test(groups = {"NegativeTests"}, enabled = false)
public void testMethodB() {
//write your test logic here
}
111. Explain the concept of parallel test execution in Selenium. What tools or frameworks can be used for parallel execution?
Parallel test execution in Selenium refers to running multiple test cases simultaneously rather than sequentially, significantly reducing the overall testing time. This approach enhances efficiency and accelerates the feedback loop. Several tools and frameworks support parallel execution in Selenium, including TestNG, JUnit, and Selenium Grid. These tools help manage and distribute test cases across multiple threads or machines, optimizing resource utilization and speeding up the testing process.
112. How can we execute test cases in parallel using TestNG?
To execute the tests in parallel, simply add these two key-value pairs to the suite:
parallel=”{methods/tests/classes}”
thread-count=”{number of threads you want to run simultaneously}”.
<suite name="TestSuite" parallel="methods" thread-count="5">
Check Running Selenium Tests in parallel for details.
113. What is the use of @Factory annotation in TestNG?
The @Factory annotation facilitates dynamic execution of test cases. By using @Factory, we can pass parameters to an entire test class at runtime. These parameters can then be utilized by one or more test methods within the class.
For example – there are two classes TestClass and the TestFactory class. Because of the @Factory annotation, the test methods in class TestClass will run twice with the data “Dataset1” and “Dataset2”.
public class TestClass{
private String str;
//Constructor
public TestClass(String str) {
this.str = str;
}
@Test
public void TestMethod() {
System.out.println(str);
}
}
public class TestFactory{
//The test methods in class TestClass will run twice with data "Dataset1" and "Dataset2"
@Factory
public Object[] factoryMethod() {
return new Object[] { new TestClass("Dataset1"), new TestClass("Dataset2") };
}
}
114. What is the difference between @Factory and @DataProvider annotation?
The @Factory method generates instances of a test class and executes all its test methods with varying data sets. In contrast, the @DataProvider is linked to individual test methods, running each specific method multiple times with different data.
Selenium Tricky Interview Questions
115. How do you handle dynamic elements in Selenium WebDriver?
In automation, we often encounter scenarios in which the application to be automated has certain elements whose locators are dynamic or in other way not known beforehand. These elements may change their attributes, IDs, or positions within the DOM during runtime.
Handling dynamic elements in Selenium WebDriver requires a flexible and adaptive approach, as these elements can change frequently on the web page. Here are several strategies to manage dynamic elements effectively:
Explicit Waits: Utilize WebDriver’s `WebDriverWait` along with expected conditions to wait for an element to be present, visible, or clickable. This allows the script to pause execution until the dynamic element is ready.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement dynamicElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("dynamicElementId")));
Dynamic Locators: Use XPath and CSS Selectors that adapt to changing elements. Relative locators or locators based on partial text or attributes can help identify elements even if they change slightly.
WebElement dynamicElement = driver.findElement(By.xpath("//div[contains(@class, 'dynamic-class')]"));
JavaScript Executor: In cases where traditional locators fail, you can use JavaScript to interact with dynamic elements directly.
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement dynamicElement = (WebElement) js.executeScript("return document.querySelector('.dynamic-selector');");
Handling Stale Element Exceptions: When dealing with elements that frequently update or reload, you might encounter `StaleElementReferenceException`. Wrap your code in try-catch blocks and re-fetch the element if necessary.
WebElement dynamicElement;
try {
dynamicElement = driver.findElement(By.id("dynamicElementId"));
} catch (StaleElementReferenceException e) {
dynamicElement = driver.findElement(By.id("dynamicElementId"));
}
116. How do you handle SSL certificate errors in Selenium?
To bypass SSL certificate errors, we can create a custom ChromeOptions object and set the –ignore-certificate-errors flag.
117. What are headless browsers in Selenium, and when should they be used?
Headless browsers in Selenium are browsers that operate without a graphical user interface. They are particularly useful for scenarios where you need to run automated tests efficiently without the overhead of rendering a visual interface.
118. Can you provide insights on best practices for creating maintainable and robust Selenium automation scripts?
Best Practices for Creating Maintainable and Robust Selenium Automation Scripts are as follows:
- Modular Test Design: Break down your test scripts into smaller, reusable modules. This will help in managing and maintaining the code efficiently. Functions, methods, and classes should be designed to perform specific tasks that can be reused across multiple test cases.
- Page Object Model (POM): Implementing the Page Object Model helps in keeping the test scripts clean and easy to understand. Each web page or component is represented by a class, with methods corresponding to actions that can be performed on the page.
- Descriptive Naming Conventions: Use descriptive names for your test methods, variables, and files. This makes the codebase easier to read and understand, aiding future maintenance.
- Consistent Locators: Use reliable locators for web elements. Prefer `id` and `name` attributes as they are less likely to change. Avoid using locators based on the element’s position, as these can be prone to breaking with minor UI changes.
- Error Handling and Reporting: Implement comprehensive error handling to manage exceptions and edge cases. Generate detailed test reports that provide insights into the failures, making debugging easier.
- Data-Driven Testing: Separate the test scripts from the test data by using external data sources like CSV, Excel, or databases. This approach allows you to run the same script with multiple sets of data, enhancing test coverage.
- Version Control: Use version control systems like Git to manage your code. This facilitates collaboration among team members and maintains a history of changes, enabling rollback if something goes wrong.
- CI/CD Integration: Integrate your Selenium tests with Continuous Integration/Continuous Deployment (CI/CD) pipelines. This ensures that your automation scripts are triggered with every build, providing immediate feedback on the health of the application.
By adhering to these best practices, you can create Selenium automation scripts that are not only robust but also easy to maintain, scale, and adapt to future changes.
119. What is the role of the WebDriverManager library in Selenium automation, and why is it useful?
The WebDriverManager library in Selenium automation simplifies the management of browser drivers. Traditionally, Selenium tests require compatible versions of browser drivers (such as Chromedriver, Geckodriver, etc.) to interact with web browsers. Manually downloading, configuring, and maintaining these drivers can be tedious and error-prone.
WebDriverManager automates this process by dynamically downloading the appropriate driver binary, configuring it, and ensuring that the driver is up-to-date. This library eliminates the need for hardcoding paths to driver executables, which significantly reduces setup time and prevents version compatibility issues. As a result, WebDriverManager enhances test reliability and simplifies the continuous integration pipeline by ensuring that the latest and most appropriate drivers are always available.
120. Explain how you would handle cross-browser testing using Selenium. What challenges can arise in this context?
To handle cross-browser testing using Selenium, you must ensure that your Selenium scripts run seamlessly across various web browsers, such as Chrome, Firefox, Safari, and Edge. This involves writing generic, browser-agnostic test scripts, avoiding browser-specific code, and leveraging WebDriverManager to manage driver binaries dynamically.
You can achieve cross-browser testing by setting up browser-specific WebDriver instances within your test framework and configuring test suites to run on different browsers using test execution tools like TestNG or JUnit in conjunction with Selenium Grid. Selenium Grid allows you to distribute tests across multiple machines and browsers, optimizing the execution process.
Challenges in cross-browser testing include handling browser-specific quirks, differences in how HTML and CSS are rendered, and varying levels of support for web technologies (such as HTML5 and CSS3) across browsers. Browser-specific bugs can also arise, necessitating thorough test validation on each browser. Additionally, ensuring consistent performance and behavior across various browser versions adds another layer of complexity to cross-browser testing. To mitigate these challenges, thorough planning, robust test design, and continuous monitoring and updating of test suites are essential.
121. How do you address synchronization challenges in Selenium when working with asynchronous web applications?
Addressing synchronization challenges in Selenium when working with asynchronous web applications requires a thoughtful approach to ensure that the tests wait for the necessary elements or events to be in the desired state before proceeding. One primary technique to handle synchronization is using explicit waits. An explicit wait allows you to specify conditions and the maximum wait time for those conditions to be met before continuing. This method is particularly useful for waiting until elements become visible, clickable, or are present in the DOM.
Another effective strategy is leveraging implicit waits, which set a default waiting time for the entire test duration. Although less granular than explicit waits, implicit waits can serve as a catch-all for general synchronization needs and can help prevent instances where elements are not found due to timing issues.
Fluent wait is another advanced technique in Selenium that provides more flexibility than explicit and implicit waits by combining waiting time with specific polling frequency and custom conditions. This approach allows for more nuanced control over synchronization.
Additionally, it’s critical to implement proper exception handling for scenarios where elements do not meet the expected conditions within the allotted time. Combining these strategies with thorough test planning and continuous monitoring can significantly improve synchronization handling in Selenium when dealing with asynchronous web applications.
122. What is BDD (Behavior Driven Development)?
Behavior Driven Development (BDD) is an agile software development process that encourages collaboration among developers, QA teams, and non-technical stakeholders. BDD aims to enhance shared understanding by defining the behavior of software through examples in plain language. These examples can then serve as the basis for automated tests, ensuring that the system’s behavior aligns with its requirements.
In BDD, scenarios are typically written in a Given-When-Then format, which outlines the context, the action, and the expected outcome. This approach helps to bridge the gap between technical and business teams, improving communication and reducing misunderstandings.
By incorporating BDD into the development process, teams can ensure that they are building the right features and that these features are thoroughly tested, leading to higher-quality software and a more efficient development cycle.
123. What is Gherkin?
Gherkin is a domain-specific language used in Behavior-Driven Development (BDD) to describe software behaviors and features in a way that is understandable to both technical and non-technical stakeholders.
Gherkin syntax is simple yet expressive, enabling the definition of test scenarios in plain text using a structured format. These scenarios typically begin with keywords such as “Given,” “When,” “Then,” which outline preconditions, trigger events, and expected outcomes, respectively. By writing tests in Gherkin, teams can ensure that everyone, from developers to business analysts, has a clear and consistent understanding of the application requirements.
124. What is the same-origin policy and how is it handled?
The same-origin policy is a critical security measure implemented in web browsers to restrict how documents or scripts loaded from one origin can interact with resources from another origin. An “origin” in this context refers to a combination of the scheme (protocol), host (domain), and port. This policy is designed to prevent malicious sites from interfering with the data or scripts of another site, thereby protecting sensitive user information and maintaining the integrity of web applications.
To handle scenarios involving same-origin policy, web developers often use techniques such as Cross-Origin Resource Sharing (CORS) to selectively allow cross-origin requests. CORS introduces HTTP headers that let servers specify which origins are permitted to access their resources. It’s essential to configure these headers accurately to ensure security while enabling the required functionality.
Additionally, other secure practices like JSONP (JSON with Padding) or utilizing server-side proxies can be employed to manage cross-origin interactions safely. JSONP is a technique that allows scripts to be loaded from a different domain by wrapping the response in a function call. Proxy is a server that acts as an intermediary between the client and the server and can be used to access resources from a different domain.
125. What is heightened privileges browsers?
A heightened privileges browser is a web browser that has been granted elevated access permissions compared to a standard browser. This means it can perform certain actions and access specific resources on a system that regular browsers cannot. These privileges may allow the browser to interact more deeply with the operating system, modify settings, or run scripts with higher authority. While having these enhanced capabilities can be useful for certain tasks, it also requires careful management to prevent potential security risks.
126. Can we verify PDF content with Selenium?
While Selenium is a powerful tool for automating web browsers, it is not designed to directly handle or verify PDF content. Selenium excels at interacting with web elements like buttons, forms, and links on HTML pages but lacks native support for PDF manipulation. To verify PDF content, you would typically need to download the PDF file and use a dedicated library like `PyPDF2` or `PDFMiner` in Python. These libraries allow you to read and extract text, metadata, and other information from PDF files, enabling you to perform content verification. By combining Selenium for web automation and a PDF library for PDF handling, you can create a robust testing framework that addresses both web and document verification needs.
127. Is it necessary to use Selenium Server to run Selenium WebDriver scripts?
No, it is not necessary to use Selenium Server to run Selenium WebDriver scripts for all scenarios. Selenium Server is required only under specific conditions, such as when you need to run your WebDriver tests on a remote machine or in a distributed testing environment. This involves setting up a client-server architecture where the server acts as a middleman, controlling the browser instances on different machines via WebDriver.
For local execution of WebDriver scripts, you can directly run your tests without the need for Selenium Server. Simply install the appropriate WebDriver executable for your browser (e.g., ChromeDriver for Google Chrome or GeckoDriver for Mozilla Firefox) and ensure it is available in your system’s PATH. This setup allows for the direct communication between your test scripts and the browser, making the execution process simpler and quicker for local tests.
128. Explain how you can handle colors in Selenium WebDriver?
Handling colors in Selenium WebDriver involves capturing the color properties of web elements and verifying them against expected values. Here are the steps to handle colors in Selenium WebDriver:
Locate the Web Element: Use Selenium WebDriver’s functions to locate the web element whose color you want to check. This can be done using various locator strategies such as `id`, `className`, `cssSelector`, `xpath`, etc.
WebElement element = driver.findElement(By.cssSelector("your-css-selector"));
Retrieve CSS Property: To get the color of a web element, retrieve its CSS property using the `getCssValue` method. For instance, to get the background color, you would use:
String color = element.getCssValue("background-color");
Convert Color Format: The retrieved color value is typically in the `rgba` format. If a comparison is needed in a different format like hexadecimal, you can use utility libraries to convert the color format. Here is how you can convert `rgba` to `hex` in Java:
Color color = Color.fromString(element.getCssValue("background-color"));
String hexColor = String.format("#%02x%02x%02x", color.getRed(), color.getGreen(), color.getBlue());
Assert the Color: Finally, compare the obtained color value with the expected value to perform the verification.
Assert.assertEquals("#ffffff", hexColor);
By following these steps, you can effectively handle and verify colors within your Selenium WebDriver tests, ensuring your web application’s UI elements are styled as expected.
129. What are the areas where Selenium can improve its features?
While Selenium is a powerful and widely used automation framework, there are several areas where it could potentially improve its features:
- Enhanced Cross-Browser Testing: Although Selenium supports multiple browsers, ensuring seamless compatibility and performance across all browser types and versions can be enhanced. There is always room for improving support for new and emerging browsers.
- Better Integration with CI/CD Pipelines: Simplifying and providing more out-of-the-box support for integrating with various Continuous Integration/Continuous Deployment (CI/CD) tools and workflows can streamline the automation process for development teams.
- Improved Parallel Test Execution: Optimizing the framework to manage and execute tests in parallel more efficiently can significantly reduce test execution time, especially for large test suites.
- User-Friendly Reporting and Debugging: Enhanced built-in reporting capabilities and debugging tools can help users quickly identify issues and understand test results without requiring additional third-party tools.
- Robust Handling of Dynamic Elements: Improving the way Selenium handles dynamically changing elements on a web page can enhance the reliability and stability of test scripts.
- Simpler Configuration and Setup: Reducing the complexity of setting up Selenium Grid and WebDriver configurations can make it more accessible to new users.
- Support for Mobile Testing: Expanding and integrating more comprehensive support for mobile testing, including native and hybrid applications, can make Selenium a more versatile tool.
By addressing these areas, Selenium can continue to evolve and remain a premier choice for web application testing.
130. What is a proxy server in Selenium?
A proxy server in Selenium acts as an intermediary between the Selenium automation script and the target web application. It captures and controls the network traffic that passes through it, allowing testers to modify, intercept, or inspect the HTTP requests and responses. This can be particularly useful for debugging, performance testing, and security testing. By configuring Selenium to use a proxy server, testers can manipulate network conditions, such as simulating slow network speeds or testing how the application behaves with different types of network fragmentation. Proxy servers also help in bypassing geo-restrictions and testing for multi-regional functionalities, making them a versatile tool in the Selenium testing toolkit.
To utilize a proxy server in Selenium, you must configure the web driver with the proxy server’s address and port number. Alternatively, you can use third-party libraries to streamline the process.
131. How to Use a Proxy Server in Selenium?
Using a proxy server in Selenium involves configuring the web driver to route its network traffic through the specified proxy. Here’s a step-by-step guide on how to set it up:
Install Selenium and WebDriver: Ensure that you have Selenium and the appropriate WebDriver for your browser installed. You can install Selenium via pip:
pip install selenium
Set Up Proxy Configuration: Create a proxy configuration with the proxy server’s address and port number. Here’s an example of how to do this in Python:
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = 'your_proxy_address:port'
proxy.ssl_proxy = 'your_proxy_address:port'
capabilities = webdriver.DesiredCapabilities.CHROME
proxy.add_to_capabilities(capabilities)
Initialize WebDriver with Proxy: Now, use the configured capabilities to initialize the WebDriver:
driver = webdriver.Chrome(desired_capabilities=capabilities)
driver.get('http://example.com')
Using Proxy with Other Browsers: For other browsers such as Firefox, you can use similar steps but with the appropriate WebDriver. Here’s how you can set up a proxy in Firefox:
from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType
proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = 'your_proxy_address:port'
proxy.ssl_proxy = 'your_proxy_address:port'
firefox_capabilities = webdriver.DesiredCapabilities.FIREFOX
proxy.add_to_capabilities(firefox_capabilities)
driver = webdriver.Firefox(capabilities=firefox_capabilities)
driver.get('http://example.com')
Verify the Proxy Setup: Access web resources through the WebDriver instance to ensure that all traffic is successfully routed through the proxy server. You can verify this by checking the proxy server logs or using specific websites that display your current IP address.
These steps help ensure that your automated tests reflect real-world conditions, especially when dealing with network-related functionalities or geo-restrictions. Using a proxy server in Selenium can enhance your testing capabilities by providing greater control over network interactions.
132. What is a User Agent in Selenium?
A user agent is a string that conveys information about the web browser and operating system used to access a website. This string is generally sent by the web browser as part of the HTTP request headers when requesting a web page.
In Selenium, the user agent can be set or modified using the webdriver library in various programming languages such as Python, Java, or C#. Customizing the user agent enables you to simulate different web browsers or devices, allowing Selenium scripts to mimic their behavior during automated web testing.
Setting a user agent in Selenium is invaluable for testing a website’s responsiveness and compatibility across diverse browsers, devices, and operating systems. By altering the user agent, Selenium can emulate different web browsers like Chrome, Firefox, Safari, or Internet Explorer, or simulate visits from various devices, including desktop computers, mobile phones, or tablets. This capability ensures that testers can verify a website’s functionality and appearance across multiple platforms and devices.
133. How to set a user agent in Selenium?
Setting a user agent in Selenium can be essential for mimicking different browsers or devices during automated testing. A user agent string helps the server understand the client making the request, enabling simulations of various environments. Here’s how you can set a user agent in Selenium:
For Chrome
To set a user agent in Chrome using Selenium, you need to customize the ChromeOptions. Below is a sample implementation in Python:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('user-agent=your-custom-user-agent-string')
driver = webdriver.Chrome(options=options)
driver.get('http://www.example.com')
Replace `your-custom-user-agent-string` with the desired user agent.
For Firefox
Firefox requires a similar setup using the FirefoxProfile. Here is an example:
from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "your-custom-user-agent-string")
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('http://www.example.com')
Again, ensure you replace `your-custom-user-agent-string` with the appropriate user agent string.
By setting the user agent, you can ensure your automated tests simulate the behavior of different devices or browsers, providing a more comprehensive testing environment.
134. How to handle hidden elements in Selenium WebDriver?
We can handle hidden elements by using javaScript executor
(JavascriptExecutor(driver)).executeScript("document.getElementsByClassName(ElementLocator).click();");
135. How can you find Broken Links in a page using Selenium WebDriver?
136. How to find more than one web element in the list?
// To store the list List <WebElement> eleList = driver.findElements(By.xpath("xpath")); // To fetch the size of the list int listSize = eleList.size(); //for loop for (int i=0; i<listSize; i++) { // Clicking on each link links.get(i).click(); // Navigating back to the previous page that stores the links driver.navigate().back(); }
137. How to read a JavaScript variable in Selenium WebDriver?
By using JavascriptExecutor
// To initialize the JS object. JavascriptExecutor JS = (JavascriptExecutor) webdriver; // To get the site title. String title = (String)JS.executeScript("return document.title"); System.out.println("Title of the webpage : " + title);
138. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?
In general, we click on an element using click() method in Selenium.
For example:
driver.findElement(By.id("Id Value")).click();
Sometimes web controls don’t react well against selenium commands and we may face issues with the above statement (click()). To overcome such kind of situation, we use JavaScriptExecutor interface.
It provides a mechanism to execute Javascript through Selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.
There is no need to write a separate script to execute JavaScript within the browser using Selenium WebDriver script. Just we use predefined interface named ‘Java Script Executor’. We need to import the JavascriptExecutor package in the script.
Package:
import org.openqa.selenium.JavascriptExecutor;
Syntax:
JavascriptExecutor js = (JavascriptExecutor) driver; js.executeScript(Script,Arguments);
Script – The JavaScript to execute
Arguments – The arguments to the script(Optional). May be empty.
Returns – One of Boolean, Long, String, List, WebElement, or null.
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method
2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using Selenium
11. To click on a SubMenu which is only visible on mouse hover on Menu
12. To navigate to different page using Javascript
139. How do you read test data from excels?
Test data can efficiently be read from excel using JXL or POI API. POI API has many advantages than JXL.
Click here to see a practical example of using Apache POI.
140. Is it possible to automate the captcha using Selenium?
Automating Captcha is a challenging task due to its design purpose, which is to differentiate humans from automated systems. Captchas include various forms such as image recognition, text transcription, or even complex puzzles that require human intuition and problem-solving skills to solve.
While it is technically possible to automate some Captchas using advanced technologies like optical character recognition (OCR), machine learning, and artificial intelligence, doing so often undermines the security purposes Captchas serve. Moreover, automating Captchas may violate the terms of service of many websites. Consequently, it is advised to find alternative ways to address automation needs without attempting to bypass security mechanisms like Captchas.
Must read: Artificial Intelligence in Software Testing
141. Is it possible to test APIs or web services with Selenium Webdriver?
No, Selenium WebDriver relies on the browser’s native methods to automate web applications. Therefore, it does not support testing web services using Selenium WebDriver.
142. Can You Use Selenium For Rest API Testing Or Web Services Testing?
Simple answer for this is Selenium is not a tool for API Testing. It automates web browsers. Rest API & Web Services contains no UI. So we cannot automate using Selenium.
Don’t miss: API Testing Interview Questions
143. How to handle Ajax calls in Selenium WebDriver?
Handling AJAX calls is one of the common issues when using Selenium WebDriver. We wouldn’t know when the AJAX call would get completed and the page has been updated. In this post, we see how to handle AJAX calls using Selenium.
AJAX stands for Asynchronous JavaScript and XML. AJAX allows the web page to retrieve small amounts of data from the server without reloading the entire page. AJAX sends HTTP requests from the client to server and then process the server’s response without reloading the entire page. To handle AJAX controls, wait commands may not work. It’s just because the actual page is not going to refresh.
When you click on a submit button, the required information may appear on the web page without refreshing the browser. Sometimes it may load in a second and sometimes it may take longer. We have no control over loading time. The best approach to handle this kind of situations in selenium is to use dynamic waits (i.e. WebDriverWait in combination with ExpectedCondition)
Some of the methods which are available are as follows:
1. titleIs() – The expected condition waits for a page with a specific title.
wait.until(ExpectedConditions.titleIs(“Deal of the Day”));
2. elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath")));
3. alertIsPresent() – The expected condition waits for an alert box to appear.
wait.until(ExpectedConditions.alertIsPresent()) !=null);
4. textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.
wait.until(ExpectedConditions.textToBePresentInElement(By.id(“title’”), “text to be found”));
144. List some scenarios which we cannot automate using Selenium WebDriver?
1. Bitmap comparison is not possible using Selenium WebDriver
2. Automating Captcha is not possible using Selenium WebDriver
3. We can not read bar code using Selenium WebDriver
145. What is Object Repository in Selenium WebDriver?
Object Repository is used to store element locator values in a centralized location instead of hard coding them within the scripts. We do create a property file (.properties) to store all the element locators and these property files act as an object repository in Selenium WebDriver.
146. How you build Object Repository in your project?
In QTP, there is an Object Repository concept. When a user records a test, the objects and its properties are captured by default in an Object Repository. QTP uses this Object Repository to play back the scripts.
Coming to Selenium, there is no default Object Repository concept. It doesn’t mean that there is no Object Repository in Selenium. Even though there is no default one still we could create our own. In Selenium, we call objects as locators (such as ID, Name, Class Name, Tag Name, Link Text, Partial Link Text, XPath, and CSS).
Object repository is a collection of objects. One of the ways to create Object Repository is to place all the locators in a separate file (i.e., properties file). But the best way is to use Page Object Model.
In the Page Object Model Design Pattern, each web page is represented as a class. All the objects related to a particular page of a web application are stored in a class.
147. What is Page Object Model in Selenium?
Page Object Model is a Design Pattern which has become popular in Selenium Test Automation. It is widely used design pattern in Selenium for enhancing test maintenance and reducing code duplication.
Page object model (POM) can be used in any kind of framework such as modular, data-driven, keyword driven, hybrid framework etc.
A page object is an object-oriented class that serves as an interface to a page of your Application Under Test(AUT). The tests then use the methods of this page object class whenever they need to interact with the User Interface (UI) of that page.
The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently, all changes to support that new UI is located in one place.
148. What is Page Factory?
We have seen that ‘Page Object Model’ is a way of representing an application in a test framework. For every ‘page’ in the application, we create a Page Object to reference the ‘page’ whereas a ‘Page Factory’ is one way of implementing the ‘Page Object Model’.
149. What is the difference between Page Object Model (POM) and Page Factory?
Page Object is a class that represents a web page and hold the functionality and members.
Page Factory is a way to initialize the web elements you want to interact with within the page object when you create an instance of it.
150. What are the advantages of Page Object Model Framework?
Code reusability – We could achieve code reusability by writing the code once and use it in different tests.
Code maintainability – There is a clean separation between test code and page specific code such as locators and layout which becomes very easy to maintain code. Code changes only on Page Object Classes when a UI change occurs. It enhances test maintenance and reduces code duplication.
Object Repository – Each page will be defined as a java class. All the fields in the page will be defined in an interface as members. The class will then implement the interface.
Readability – Improves readability due to clean separation between test code and page specific code
151. How can you use the Recovery Scenario in Selenium WebDriver?
By using “Try Catch Block” within Selenium WebDriver Java tests.
try { driver.get("www.softwaretestingmaterial.com"); }catch(Exception e){ System.out.println(e.getMessage()); }
152. How to Upload a file in Selenium WebDriver?
There are two cases which are majorly used to upload a file in Selenium WebDriver such as using SendKeys Method and using AutoIT Script.
153. How to Download a file in Selenium WebDriver?
By using AutoIT script, we could download a file in Selenium WebDriver.
154. How to run Selenium WebDriver Test from the command line?
155. How to switch between frames in Selenium?
By using the following code, we could switch between frames.
driver.switchTo().frame();
156. How to connect a Database in selenium?
As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.
We use JDBC Driver to connect the Database in Selenium (While using Java Programming Language).
157. How To Resize Browser Window Using Selenium WebDriver?
To resize the browser window to particular dimensions, we use ‘Dimension’ class to resize the browser window.
158. How To Scroll Web Page Down Or UP Using Selenium WebDriver?
JavaScript scrollBy() method scrolls the document by the specified number of pixels.
159. How To Perform Right Click Action (Context Click) In Selenium WebDriver?
We use Actions class in Selenium WebDriver to do Right-Click (Context Click) action.
160. How To Perform Double Click Action In Selenium WebDriver?
We use Actions class to do Double click action in selenium.
161. How To Perform Drag And Drop Action in Selenium WebDriver?
In some applications, we may face a situation to automate drag and drop an item from one location to another location. We could not achieve these using basic elements. Selenium has provided an “Actions” class to handle this kind of scenarios. We overcome this kind of scenarios such as drag and drop using Actions Class.
To achieve this, we use Actions class in Selenium WebDriver.
162. How To Highlight Element Using Selenium WebDriver?
By using JavascriptExecutor interface, we could highlight the specified element
163. Have you used any crossbrowsertesting tool to run selenium scripts on cloud?
I have used BrowserStack to run selenium tests on multiple browsers & Multiple operating systems in parallel. Earlier we have made a video on how to use BrowserStack to run selenium scripts on the cloud. Find the link in the description below.
164. What is desired capabilities?
In Selenium we use desired capabilities to handle SSL certificates in chrome browser
We need to create an instance of DesiredCapabilities
DesiredCapabilities desiredCapability = DesiredCapabilities.chrome();
165. What is Continuous Integration?
Continuous Integration is abbreviated as CI. Continuous Integration is a development practice that aims to make sure the correctness of software. After each commit, a suite of tests run automatically and test the software to ensure whether the software is running without any breaks. If any test fails, we will get immediate feedback say “build is broken”.
In simple words, continuous integration is a process of verifying the correctness of a software.
Some of the continuous integration tools are Jenkins, TeamCity, Bamboo, Travis, Circle Ci, Bitbucket.
We can schedule the test suite execution using these CI Tools.
Learn how Continuous Integration with Jenkins in Selenium works
166. Name some CI tools available in the Market?
Some of the best continuous testing softwares to use in your project.
- Selenium
- Katalon Studio
- Appium
- Unified Functional Testing
- Travis CI
- Egg Plant
- Watir
- Tricentis Tosca
- Test Sigma
- IBM Rational Functional Tester
- Test Complete
- QuerySurge
- JMeter
- Jenkins
- Bamboo
- Docker
- PagerDuty
- JIRA
- GitHub
Read the detailed explanation on Continuous Testing Tools
167. How to achieve Database testing in Selenium?
As we all know Selenium WebDriver is a tool to automate User Interface. We could only interact with Browser using Selenium WebDriver.
Sometimes, we may face a situation to get the data from the Database or to modify (update/delete) the data from the Database. If we plan to automate anything outside the vicinity of a browser, then we need to use other tools to achieve our task.
To achieve the Database connection and work on it, we need to use JDBC API Driver.
The Java Database Connectivity (JDBC) API provides universal data access from the Java programming language.
Using the JDBC API, you can access virtually any data source, from relational databases to spreadsheets and flat files. It lets the user connect and interact with the Database and fetch the data based on the queries we use in the automation script.
JDBC is a SQL level API that allows us to execute SQL statements. It creates a connectivity between Java Programming Language and the database.
Using JDBC Driver we could do the following
i. Establish a Database connection
ii. Send SQL Queries to the Database
iii. Process the results
168. How to delete Browser Cookies with Selenium Web Driver?
driver.Manage().Cookies.DeleteAllCookies();
TestNG Interview Questions:
Here we have dealt with some important TestNG interview questions. If you want to learn more interview questions related to TestNG then here you go. We have a special post on TestNG Interview Questions. Also, you could find TestNG Complete Tutorial here
169. What is TestNG?
TestNG is a testing framework designed to simplify a broad range of testing needs, from unit testing to integration testing.
170. What are the types of annotations available in TestNG?
@BeforeTest
@AfterTest
@BeforeClass
@AfterClass
@BeforeMethod
@AfterMethod
@BeforeSuite
@AfterSuite
@BeforeGroups
@AfterGroups
@Test
171. What is TestNG Assert and list out some common Assertions supported by TestNG?
TestNG Asserts help us to verify the condition of the test in the middle of the test run. Based on the TestNG Assertions, we will consider a successful test only if it is completed the test run without throwing any exception.
Some of the common assertions supported by TestNG are
- assertEqual(String actual,String expected)
- assertEqual(String actual,String expected, String message)
- assertEquals(boolean actual,boolean expected)
- assertTrue(condition)
- assertTrue(condition, message)
- assertFalse(condition)
- assertFalse(condition, message)
172. How to create and run TestNG.xml?
In TestNG framework, we need to create TestNG XML file to create and handle multiple test classes. We do configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc in the XML file.
173. How to set test case priority in TestNG?
We use priority attribute to the @Test annotations. In case priority is not set then the test scripts execute in alphabetical order.
package TestNG; import org.testng.annotations.*; public class PriorityTestCase{ @Test(priority=0) public void testCase1() { system.out.println("Test Case 1"); } @Test(priority=1) public void testCase2() { system.out.println("Test Case 2"); } }
Output:
Test Case 1 Test Case 2
174. What is Parameterized testing in TestNG?
Parameterized tests allow developers to run the same test over and over again using different values.
There are two ways to set these parameters:
- with testng.xml - Practical Example
- with Data Providers – Practical Example
175. How to run a group of test cases using TestNG?
TestNG allows you to perform sophisticated groupings of test methods. Not only can you declare that methods belong to groups, but you can also specify groups that contain other groups. Then TestNG can be invoked and asked to include a certain set of groups (or regular expressions) while excluding another set.
This gives you maximum flexibility in how you partition your tests and doesn’t require you to recompile anything if you want to run two different sets of tests back to back.
Groups are specified in your testng.xml file and can be found either under the <test> or <suite> tag. Groups specified in the <suite> tag apply to all the <test> tags underneath.
@Test (groups = { "smokeTest", "functionalTest" }) public void loginTest(){ System.out.println("Logged in successfully"); }
176. What is the use of @Listener annotation in TestNG?
Ans. TestNG listeners are used to configure reports and logging. One of the most widely used listeners in TestNG is ITestListener interface. It has methods like onTestStart, onTestSuccess, onTestFailure, onTestSkipped etc. We should implement this interface creating a listener class of our own. Next, we should add the listeners annotation (@Listeners) in the Class which was created.
177. How can we create a data-driven framework using TestNG?
By using @DataProvider annotation, we can create a Data-Driven Testing Framework.
@DataProvider(name="getData") public Object[][] getData(){ //Object [][] data = new Object [rowCount][colCount]; Object [][] data = new Object [2][2]; data [0][0] = "FirstUid"; data [0][1] = "FirstPWD"; data[1][0] = "SecondUid"; data[1][1] = "SecondPWD"; return data; }
178. Where you have applied OOPS in Automation Framework?
Here we have given a clear explanation of the application of OOPs in Automation Framework
179. How to handle browser (chrome) notifications in Selenium?
In Chrome, we can use ChromeOptions as shown below.
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);
I would like to conclude this post here. Final words, Bookmark this post “Selenium Testing Interview Questions” for future reference. We keep on updating this post based on user requests.
180. Mention types of data you have handled in Selenium?
- Excel
- CSV
- XML
- JSON
- YAML
- SQL
Selenium Scenario-Based Interview Questions
181. You are testing an e-commerce website, and during checkout, the ‘Place Order’ button is not consistently responding. How would you use Selenium to debug and resolve this issue?
To debug and resolve the issue where the ‘Place Order’ button is not responding consistently during checkout, follow these steps using Selenium:
Verify Element Visibility: Ensure that the ‘Place Order’ button is visible and enabled before attempting to click it. Use assertions to check the visibility and state of the button:
button = driver.find_element_by_id('place-order-button-id')
assert button.is_displayed() and button.is_enabled()
Check for JavaScript Errors: Console errors can often disrupt the functionality of elements on a page. Use browser logs to check for any JavaScript errors that might be impacting the ‘Place Order’ button:
for entry in driver.get_log('browser'):
print(entry)
Implement Explicit Waits: Sometimes elements may not be interactable immediately. Use WebDriverWait to wait for the ‘Place Order’ button to be clickable:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
button = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.ID, 'place-order-button-id'))
)
button.click()
Investigate Element Overlap: Ensure no other elements overlap with the ‘Place Order’ button, preventing it from being clicked. Check for overlapping elements using JavaScript:
driver.execute_script("return document.elementFromPoint(arguments[0], arguments[1]);", button.location['x'], button.location['y'])
Check for Dynamic Changes: Sometimes the user interface dynamically changes, causing the button to become unresponsive. Observe if there are any styles or property changes:
initial_class = button.get_attribute("class")
# Perform actions that could potentially cause changes
final_class = button.get_attribute("class")
assert initial_class == final_class
By systematically applying these debugging techniques, you can identify the root cause of the inconsistent behavior and take appropriate measures to ensure the ‘Place Order’ button functions correctly during checkout.
182. The application you are testing includes a file upload feature. Describe how you would automate the file upload testing using Selenium WebDriver.
To automate the file upload testing using Selenium WebDriver, you can follow a systematic approach leveraging the capabilities of the WebDriver to interact with the file input elements. Here’s a comprehensive guide to achieve this:
Identify the File Upload Element: First, locate the file upload element on the webpage. Typically, this would be an input element of type file.
file_input = driver.find_element(By.ID, "file-upload-input-id")
Prepare the File Path: Ensure you have the path to the file you want to upload. This file needs to be accessible from the machine where your WebDriver tests are running.
file_path = "/path/to/your/file.txt"
Upload the File: Use the `send_keys` method to input the path of the file into the file upload element. This simulates the action of a user choosing a file from their file system.
file_input.send_keys(file_path)
Trigger the Upload Process: If there is a button or mechanism to trigger the upload process after selecting the file, find that element and simulate a click event.
upload_button = driver.find_element(By.ID, "upload-button-id")
upload_button.click()
Verify the Upload: After uploading the file, verify that the file has been successfully uploaded. This could involve checking for a success message, the presence of the file in a list, or any other confirmation the application provides.
success_message = driver.find_element(By.ID, "upload-success-message-id")
assert success_message.is_displayed()
By following these steps, you can effectively automate the file upload testing process using Selenium WebDriver. This ensures that the file upload functionality works correctly and reliably within the application.
183. While running your Selenium tests, you encounter intermittent failures due to dynamic elements. Describe strategies to handle dynamic elements effectively and maintain test stability.
Intermittent failures caused by dynamic elements can significantly impact the stability of your Selenium tests. Here are some strategies to handle these elements effectively:
Explicit Waits: Utilize explicit waits to wait for a certain condition to be met before proceeding with the next step. This is particularly useful for elements that take time to appear or become clickable.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "dynamic-element-id"))
)
Implicit Waits: Set an implicit wait to instruct the WebDriver to poll the DOM for a certain amount of time when trying to find any element. This is less flexible than explicit waits but can be useful as a global timeout setting.
driver.implicitly_wait(10) # seconds
Retry Mechanism: Implement a retry mechanism to handle occasional failures by attempting the action multiple times.
def click_with_retry(by, value, retries=3):
for i in range(retries):
try:
element = driver.find_element(by, value)
element.click()
break
except:
if i == retries - 1:
raise
time.sleep(1) # Wait a bit before retrying
Action Chains: Use ActionChains for complex interactions, such as hover effects or drag-and-drop actions, which often involve dynamic elements.
from selenium.webdriver.common.action_chains import ActionChains
element = driver.find_element(By.ID, "dynamic-element-id")
action = ActionChains(driver)
action.move_to_element(element).click().perform()
JavaScript Executor: Execute JavaScript directly if the standard WebDriver methods are not working reliably. This can force interactions with elements that are otherwise difficult to manipulate.
element = driver.find_element(By.ID, "dynamic-element-id")
driver.execute_script("arguments[0].click();", element)
Handling Stale Elements: If elements change after they are found, resulting in a `StaleElementReferenceException`, catch the exception and try to find the element again.
from selenium.common.exceptions import StaleElementReferenceException
for i in range(3):
try:
element = driver.find_element(By.ID, "dynamic-element-id")
element.click()
break
except StaleElementReferenceException:
time.sleep(1) # Wait a bit before retrying
By incorporating these strategies, you can significantly increase the reliability and stability of your Selenium tests when dealing with dynamic elements.
184. How do you handle browser cookies in Selenium WebDriver?
Handling cookies in Selenium WebDriver allows you to manage your web application’s state and user sessions effectively. Below are some common operations to manage cookies in a web application using Selenium WebDriver with Java:
Adding a Cookie: You can add a new cookie to the current session using the `addCookie` method. This is useful for setting session-specific data.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Cookie;
public class CookieExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
Cookie cookie = new Cookie("example_cookie", "cookie_value");
driver.manage().addCookie(cookie);
}
}
Getting a Cookie: Retrieve a specific cookie by name using the `getCookieNamed` method.
Cookie exampleCookie = driver.manage().getCookieNamed("example_cookie");
System.out.println(exampleCookie);
Getting All Cookies: Retrieve all cookies stored in the browser using the `getCookies` method.
Set<Cookie> allCookies = driver.manage().getCookies();
for (Cookie cookie : allCookies) {
System.out.println(cookie);
}
Deleting a Cookie: Remove a specific cookie by name using the `deleteCookieNamed` method.
driver.manage().deleteCookieNamed("example_cookie");
Deleting All Cookies: Clear all cookies from the current session using the `deleteAllCookies` method.
driver.manage().deleteAllCookies();
By utilizing these methods, you can effectively manage browser cookies in Selenium WebDriver, thereby simulating different user scenarios, maintaining user sessions, and ensuring your application performs as expected across various states.
185. How would you approach localization testing for a multilingual web application?
Localization testing ensures your multi-lingual web app meets users’ needs. Key steps include supporting language packs, verifying accurate translations, and scrutinizing the user interface for compatibility with different character sets. Additionally, it should test date/time formats, currency symbols, and regional variations.
186. How would you address a scenario where a web application relies on browser-specific features like ActiveX or Java applets?
Browser-specific features like ActiveX or Java applets can cause compatibility issues in web application automation. To address this, ensure the application communicates effectively with the browser and handles compatibility issues. Testing should include different browser versions, operating systems, and security settings. Providing alternative solutions for users who can’t use these features helps maintain accessibility and functionality.
187. How would you manage a scenario in which a web application employs security mechanisms such as SSL or OAuth?
Security mechanisms like SSL and OAuth are vital for web applications. Proper implementation and handling of these mechanisms are crucial to addressing security issues. Testing should include secure HTTPS communication, OAuth token-based authentication, and encrypted storage of user credentials.
188. How would you manage a web application that relies on third-party plugins such as Adobe Flash or Microsoft Silverlight?
Third-party plugins like Adobe Flash or Microsoft Silverlight can cause compatibility issues in automated web applications. Ensuring proper communication and handling between the application and plugins is crucial. Testing should address browser versions, operating systems, and plugin security settings to mitigate these issues.
189. How would you handle a scenario where a web application uses third-party APIs or services?
Handling a scenario where a web application uses third-party APIs or services requires careful integration and robust testing processes. First, it is essential to thoroughly understand the API documentation provided by the third-party service to ensure correct implementation. This includes knowing the endpoints, required authentication methods, request formats, and expected responses. Using API clients like Postman can help in testing API calls and understanding their behavior before integrating them into the application.
Once integrated, unit tests and integration tests should be developed to validate the interaction between the application and the third-party service. These tests should cover various scenarios such as successful responses, error handling, and edge cases. It is also crucial to handle timeout scenarios and implement retries for transient failures to ensure reliability.
Security considerations are paramount. Secure the API keys and tokens by storing them in environment variables or using a secrets management service. Ensure that sensitive data transmission between your application and the third-party service is encrypted using HTTPS. Moreover, regularly review and update the integration to adapt to any changes in the third-party API, including version updates and deprecated endpoints.
By taking these measures, you can ensure that the integration with third-party APIs or services is seamless, reliable, and secure, thereby enhancing the functionality and user experience of your web application.
190. How would you handle a scenario where a web application has dynamic URLs?
Managing dynamic URLs in web applications requires a structured approach to ensure proper routing, security, and user experience. Implementing a consistent URL structure with descriptive keywords and URL rewriting enhances SEO and user readability. Proper handling of URL parameters, using canonical tags, and setting up redirects help avoid common issues like duplicate content and broken links. Employing automated testing tools and regular monitoring ensures all URL variations work correctly, contributing to the overall success of the web application.
191. How would you manage a scenario where a web application utilizes intricate data structures such as trees or graphs?
Handling complex data structures like trees or graphs in a web application necessitates the use of efficient algorithms and data management strategies. It’s crucial to thoroughly understand their fundamental data models and their impact on application functionality. Achieving optimal performance requires utilizing efficient algorithms and data structures for manipulating or traversing these models. Additionally, rigorous testing procedures are essential to safeguard data integrity and address potential memory allocation or resource issues.
192. How would you manage a scenario where a web application relies heavily on AJAX calls to update its UI?
AJAX calls enhance website dynamism but can complicate automation. Testing is crucial for effective communication with third-party APIs, handling errors like network outages, rate limiting, and invalid responses. Secure authentication, error handling, and logging are vital, along with regular testing to ensure continued operation despite changes in external services.
193. How can you optimize your Selenium scripts for speed and performance?
To optimize Selenium scripts for speed and performance, reduce page refreshes, use conditional waits, and employ headless browsers or cloud services for parallel testing. Efficient selectors, eliminating unnecessary requests, and minimizing logging can further enhance performance.
Selenium Tester Salary Trends
In recent years, the demand for Selenium Testers has seen a significant rise in the IT industry, and with it, competitive salary packages are being offered to skilled professionals.
On average, Selenium Testers in the United States can expect to earn between $70,000 to $120,000 annually, depending on factors such as experience, location, and the specific needs of the employer.
On average, Selenium Testers in India can expect to earn between 3.4 LPA to 14 LPA, depending on factors such as experience, location, and the specific needs of the employer.
Entry-level positions typically start at the lower end of the scale, while testers with several years of experience and advanced expertise in automation frameworks can command salaries on the higher end or beyond.
Geographic location plays a crucial role in salary variations, with tech hubs like San Francisco, New York, and Seattle offering higher compensation compared to other regions.
Additionally, certifications and continuous learning can significantly enhance earning potential. As organizations increasingly prioritize automated testing to ensure the quality and reliability of their software, the salary trends for Selenium Testers are expected to remain positive, making this a lucrative career path for aspiring professionals.
Selenium MCQ Interview Questions
Take this Selenium Quiz and test your knowledge.
Selenium Real Time Interview Questions Videos
Here are some video tutorials which contain real-time selenium interview questions.
We got multiple questions from our readers. Some of them I have included here.
Selenium WebDriver Interview Questions FAQ:
Is there any selenium certification?
Usually, certifications are provided by companies that have developed a proprietary tool like QTP, AWS, Salesforce, etc., Selenium is an open-source software testing tool. There are many certification providers (training institutes) who provide certification in Selenium but Selenium is open source software, it does not offer any certification of their own. If I am in your position, I prefer certification in a programming language like Java instead of Selenium.
Can I learn selenium on my own?
You can self learn Selenium. I know many automation testers who learn selenium on their own by going through Selenium blogs like SoftwareTestingMaterial. Learn Selenium online and practice it until you feel confident. Once you become confident include your automation skills in your resume and if possible showcase your automation skills to your managers. So that you may grab an opportunity in your current organization itself.
Before learning Selenium I suggest you learn
Manual Testing concepts
Java (Core Java is fine).
Start with Java and then move on to Selenium.
What are the basics of selenium?
Selenium suite is comprised of 4 basic components namely Selenium IDE, Selenium RC, WebDriver, and Selenium Grid.
Is Selenium easy to learn?
Yes of course. Learning Selenium is easy. Check out our Selenium Tutorial
How many days it will take to learn selenium?
1-2 Months enough if you can spend at least 3-4 hours per day.
Please add Selenium interview questions for freshers
Here we have covered most of the interview questions which help you to attend Selenium Interview as a fresher.
I have three years of experience and I would like to prepare for an interview. Please include Selenium interview questions for 3 years experience.
We have covered Selenium WebDriver interview questions for 3 years experienced too.
I am working as a manual tester and applying for an automation job. Can you please list Selenium interview questions for 5 years experience etc.,
This list of 100+ Selenium Interview questions help you to crack your interview. If you have any queries, you can comment below. Our team will help you.
Conclusion
We are here to help you guys, we will include Selenium advanced interview questions frequently. Also, we are planning to provide Selenium Interview Questions and Answers PDF Download link. Check out this space again to download it.
I hope now you are ready to attend an interview. One last step before doing that. Why can’t you test your knowledge using our popular Selenium Quiz.
Here are some hand-picked posts you must read after the above 100+ Selenium Interview Questions and Answers.
- Explain Selenium Test Automation Framework
- Selenium Framework Interview Questions
- Selenium Java Interview Questions For Selenium Automation Testers
- Selenium Python Interview Questions For Selenium Testers
- Test Automation Framework Interview Questions
- Selenium Automation Interview Questions
- TestNG Interview Questions
- Why you chose Software Testing As Your Career
- Manual Testing Interview Questions
- Cypress Interview Questions
- Agile Interview Questions
- SQL Interview Questions
- 30+ Popular Cucumber Interview Questions
- Java Tutorial For Selenium Testers
If you have any more questions, feel free to ask via comments. If you find this post useful, do share it with your friends on Social Networking.
Thanks for this useful post
Hi Yem, Glad you found it useful.
Very nice post. But still there are few things to cover. i.e. handling menus, handling Web table, handling dynamic radio buttons……….
Thanks Srinivas. We will try to include those at the earliest. 🙂
exelent sir. if you dont mind tell me the bugs concept ,how to real time face the issue,where is report it ,team lead or other
Hi Lakshman, please read this to understand clearly about Bug Life Cycle.
Once a tester finds a bug, that bug needs to be reported using reporting tools (like JIRA, QC..). Concerned person will move the bug to developers (it depends on company.. either test lead or project manager)
What are the roles and responsibilities of automation qc
Hi Prajwal, It depends on experience and company. I will list some common points here.
– Participate in product design reviews to provide input on functional requirements, product design specifications and release schedules
– Develop automated test scripts for software test validation
– Develop automated test scripts,
– Involvement in collection of test data and Performs test executions
– Prepare reusable functions, which improve the robustness, reusability, and maintainability of their test scripts
– Provides an assessment of their own anticipated work effort as input to project estimation
– Involvement in Test reports, incidents, reports and traceability matrix
– Document software defects, using a bug tracking system, and report defects to software developers using HP QC, Jira, and TFS
– Work with cross functional teams to facilitate communication and adaptability within an Agile environment
Nice information Rajkumar
Thank You so much
May I know these questions are for how many years experience profiles?
Hi Mishra, these questions will be helpful for basic to advance level testers
Hello Rajkumar, I think there’s a confusion in defining the relative xpath here in quesition 28, since it starts with double forward slash(//):
Relative XPath starts from any node in between the HTML page to the current element’s node(last node of the element). It starts with a single forward slash(//) as shown below.
Good catch Barno. Modified the statement. Thanks.
I have a interview scheduled on selenium ruby, java need help preparing for the interview.
Hi Rahul, what kind of support you are looking..
How to prepare for the interview and types of questions that can be expected. I have the interview tommorw.
Sir,
Please post s
Java interview questions and answers.
Hi Sunitha Reddy. Working on that. will post it ASAP.
Hi Raj,
Having around 2 years of experience what is expectation level in the company when we switch to another company. Working in Data Driven testing how it will be helpful in future. Going forward ‘m interested to work in POM and various frameworks and want to develop Framework. so please let me know what are things i need to learn going forward to become pro like you 🙂
It depends on company you are applying for Praveen. Learn Java concepts thoroughly, it helps you build framework. POM is not a framework.. its just a design pattern.. Data Driven is fine. Check the below posts..
Page Object Model and Selenium Continuous Integration with Jenkins & Github
Hi Raj,
Nice post Please upload selenium with c# interview questions for experience.
Very useful post.
I am glad you liked it.
who create the framework
Anyone who has knowledge can create.
Glad to find this post. very useful
Thank you so much 🙂
Hi,
For Question 33:
we cannot create object to an interface, We create object to driver class (Chrome or IE or Firefox) with reference to WebDriver inteface
Good catch Aswini. I have updated that.
Rajkumar,
This is really useful for preparing interview. Also acts as guide on real time problems we encounter while day to day testing.
Great job.
Hi,
this is very useful post and questions are helping me lot in technical interview.
Please help for some question related to agile and scrum.
Hi Pranali. Thanks. Here is the link “Agile Interview Questions“
this blog helps a lot to build career as an automation engineer, thanks for providing such an helpful info
Glad you liked our articles.
Hi RajKumar,
First of all Thank you for the nice bunch of question which help to prepare quickly for the Interview.
I have a question regarding Q.39. Can you provide us a link as the usage of setSpeed(5000)?
Hi Rajib, we used to use setspeed in Selenium IDE. Now in Selenium WebDriver we use implicit wait instead of this. The same updated in the above post.
Thanks this really helps me alot to brush my concepts.
Hi Mandeep, I am glad it helped you.