Selenium
How to do mouse over?
Actions action = new actions(driver); action.moveToElement(driver.findElement(By.Xpath("......"))).build().perform();
Can you create a modified xpath? How do you do that?
I can create modified xpath. I need to inspect the web element and find the attribute I want to use as xpath. That attributes can be setup in the xpath structure to create a modified xpath. contains() : Xpath=//*[contains (@type, 'sub')] starts-with() : Xpath=//label[starts-with(@id,'message')] text() : Xpath=//td[text()='UserID']
What is your preferred locating technique?
I think locating techniques depend on the specific web application. In general, I would prefer to use an id or name to use in my code if they are unique. Xpath is also a good option. For hyperlinks, I always prefer to use link text or partial link text attributes. In my current project, I am using xpath to find most web elements and linktext for hyperlinks.
What is polling interval?
In explicit wait, the driver will try to check the element every seconds. But by polling interval, we can set the frequency of the driver to check the element in time specified by us. WebdriverWait wait1 = new WebdriverWait (driver, 60); wait1.pollingEvery(duration, unit); wait1.until(ExpectedConditions.elementToBeSelected(driver.findelement(By.Xpat h())));
What is explicit wait in selenium?
In explicit wait, you can give a timeout limit for each element. However, if an element is present before the timeout limit is reached, it will continue to execute the test script, and it doesn't need to wait for the time limit. It can also be used to replace the Thread.sleep command.
What authorization do you use? Who provides you with an access token???
OAuth 2.0 ?????? Developer
What are the different components of selenium?
Selenium IDE, Selenium RC, Selenium WebDriver, Selenium Grid
how to take a screenshot using selenium?
Selenium has provided TakesScreenShot interface by which we can use getScreenshotAs method which will help in capturing the entire screenshot in form of file then using FileUtils we can copy screenshots from one location to another location File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); try { //now copy the screenshot to desired location using copyFile method FileUtils.copyFile(src, new File("C:/selenium/error.png"));
How can I perform cross browser testing using xml file in selenium?
To conduct cross-browser testing in Selenium, an XML file is utilized to execute the same test across different browsers. The TestNG framework, along with the 'Parameters' annotation, is employed to gather browser information from the XML file and pass it to the test methods for browser configuration. In Cucumber, you can achieve cross-browser testing by integrating it with the TestNG framework, which allows you to parameterize your tests. This approach involves configuring test scenarios in TestNG XML files and utilizing the 'Parameters' annotation to pass browser-related parameters to your Cucumber step definitions.
Let's say if I don't have any values in a string array index, what will be the default value for that index?
null
Explain the line of code Webdriver driver = new FirefoxDriver();
'Webdriver' is an interface and we are creating an object of type WebDriver instantiating an object of FirefoxDriver class.
What are some tricks for Xpath?
-add a variable to the xpath by doing: "+variable+". Example: findElement(By.xpath(["//*[@id='"+variable+"']") -find elements using forward slashes in xpath and index them. -If you have multiple matches for an xpath, you can put the xpath in parenthesis; and in brackets, you can select which index you want. Ex: "//*[text()='some_text']")[2]; In this example, I am selecting the second instance of this xpath.
How to get window id on run time And How to handle multiple window?
// Get all window handles Set<String> windowHandles = driver.getWindowHandles(); // Create a list to store the handles List<String> windowIDs = new ArrayList<>(windowHandles); // Switch to the third window (index 2 since it's 0-based) driver.switchTo().window(windowIDs.get(2)); // Perform actions in the third window // Close the third window driver.close(); // Switch back to the parent window (index 0) driver.switchTo().window(windowIDs.get(0));
Let's say if I don't have any values in an integer or double array index, what will be the default value for that index?
0
What is the difference between relative and absolute xpath?
An absolute xpath contains the complete path from the root element to the desired element. Relative xpath is when you simply start by referencing the element you want and go from there. We should always use relative xpath for testing because if anything changes in the path, there will be an error in the code.
How to work with Excel file in Selenium?
Apache POI
How do you write the code to handle tabs in Selenium?
ArrayList<String> tabs = new ArrayList<String> (ddriver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); driver.close();
What are some locator commands?
Assuming 'driver' is a WebDriver object: - driver.navigate().to("https://www.website.com"); - driver.manage().window().maximize(); - driver.close(); - driver.quit(); - driver.getTitle(); - Thread.sleep(...); - driver.findElement(By.xpath("//*[...]")) - driver.findElement(By.xpath("//*[...]")).sendkeys("..."); - driver.findElement(By.xpath("//*[...]")).click(); - driver.findElement(By.xpath("//*[...]")).submit(); - driver.findElement(By.xpath("//*[...]")).getText(); - driver.findElements(By.xpath("//*[...]")).get(...).click();
*********What are ChromeOptions?
Before defining the WebDriver, ChromeOptions allows you to set multiple arguments relating to the behavior of the WebDriver, like maximize window, incognito mode, etc. They need to be called before defining the webdriver, and its object should be passed as an argument to the webdriver.
How do you type something on a search field web element?
By using the command sendkeys()
How can I locate an element using cssSelector? hint: best choice is by.Xpath but still look into by.cssSelector
CSS selector combines an element selector and a selector value, and can locate web element without ID, class, or name, like xpath. There are 5 types of CSS selectors (ID, Class, Attribute, Sub-String, Inner String). - ID: you use hash symbol: css=tagname#idValue - class: you use a dot: css=tagname.classValue - any attribute: css=tagnname[attribute='attributeValue'] - Prefix: css=tagname[attribute^=prefix_of_the_string] - Suffix: css=tagname[attribute$=suffix_of_the_string] - Match substring: css=tagname[attribute*=sub string] - Inner text: css=tagname:contains(text)
What is 'contains' in xpath?
Contains() is a method which is used to find the value of those attributes which changes dynamically. It allows us to locate any element using partial values
Is the FirefoxDriver a Class or an Interface?
FirefoxDriver is a Java class, and it implements the WebDriver interface. It is not an interface. It is a specific class provided by the Selenium WebDriver library for automating interactions with the Firefox web browser.
What is Fluent Wait?
Fluent Wait and polling interval is the same. The only difference is, fluent wait comes with default polling interval. To implement, we need to create an object of Fluent wait. Wait wait = new FluentWait(driver).withTimeout(30, SECONDS).pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class). until(ExpectedConditions.elementToBeSelected(driver.findelement(By.Xpath())));
What are the challenges and limitations of Selenium WebDriver?
Image-Based Application Testing: Mention that Selenium is primarily designed for web applications and may not handle image-based applications as effectively. This could include applications that rely heavily on graphics or images for user interaction. Reporting and Integration: Explain that Selenium doesn't have built-in reporting capabilities, so it often requires integration with other tools like TestNG or Jenkins for reporting and continuous integration. This integration can be challenging. Inability to Test Web Services: Elaborate on the fact that Selenium is mainly for UI testing and cannot directly test web services like SOAP or REST. It's important to clarify that Selenium is not the tool of choice for testing APIs. Handling Pop-Ups and Dynamic Content: Expand on these points, explaining the difficulties in handling pop-up windows or dynamic content that changes without a page reload. Mobile Application Testing: Clearly state that Selenium WebDriver is not designed for mobile ap
What is implicit wait in selenium?
Implicit wait is declared only once and applies to all web elements in the class. Once it's called, then if an element is not present at that specific time, the script will fail. It can be used to replace the Thread.sleep command. Sometimes, implicit wait locates the element in the background before it is loaded into the user interface. When this happens, the script will fail because it won't be able to interact with the element on the UI yet.
What are the types of Waits available in Selenium WebDriver?
Implicit, Explicit and Fluent wait.
What is Javascript Ready state?
It makes sure the page is completely loaded. It's a javascript executor function that uses Boolean output type to make sure the page is loaded. It also uses try and catch block to check if the page is loaded or not.
What is a JavaScriptExecutor? / How to scroll using Selenium?
JavaScriptExecutor is an Interface that helps to execute JavaScript through Selenium WebDriver. It provides two methods "executescript" & "executeAsyncScript. It is used when Selenium WebDriver fails to click on any element.
How do I execute Javascript?
JavascriptExecuter javascript = ((javascriptexecutor)driver).executeScript(arg0, arg1); [We need to cast out driver with Javascriptexecutor]
How do I select the size of the browser window?
Maximize() = Driver.manage().window.maximize() Resize the current window = Window.getSize(); Driver.manage.window.setSize(d); Set particular size = (JavaScriptExecutor)driver.executeScript("window.resizeTo(x,y)");
*****How to get the coordinates of the window?
Point position = driver.manage().window().getPosition(); Position.get(x); Position.get(y); [Point is a local variable which we get by clicking on position]
Can Selenium handle window pop-ups?
Selenium does not support handling pop-ups. Alert is used to display a warning message. It is a pop-up window that comes up on the screen. Void sendKeys(StringToSend): This is called when you want to send some data to alert box. Void dismiss(): This method is called when the 'Cancel' button is clicked in the alert box. Void accept(): This method is called when you click on the 'OK' button of the alert. String getText(): This method is called to capture the alert message.
What is selenium?
Selenium is an automation testing tool that can interact with web browsers. It is a framework that any library or browser can use. It is the third-party library used for functional testing.
What are the challenges of using selenium?
Selenium is an open source tool that can be integrated with many different tools for creating a test framework. I think one of the challenges is to find what will be the right combination of tools based on the project's requirements and exceptions. Another thing is that solving problems in Selenium for functional testing largely depends on the programming skill set of the tester. So the challenge is mostly dependent on the programmer's skills.
Why should we use Selenium?
Selenium is an open-source and free Java library. The Selenium library is available in multiple languages, including Java, C#, Java Scripts, Python, and Ruby. Also, because Selenium has become a very popular testing tool, there are a lot of online resources available for the Selenium tester to learn new things and solve existing problems.
If you cannot find an id/name or unique xpath for web elements in a page, what do you do?
Since xpath also depends on the attributes, and if there is no unique xpath, we can create a modified xpath using any attribute that is unique. The last option would be to use absolute xpath or talk with the developers to provide a unique attribute that selenium supports.
What is the difference between "/" and "//" in xpath?
Single slash is used to create absolute XPath whereas Double slash is used to create relative xpath.
What is the purpose of storing the locator as a variable?
So you can reuse the webelement if you need to. It also makes it easier to understand the code statements.
How will you work on IE and Google Chrome in WebDriver?
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); WebDriver driver = new ChromeDriver(); WebDriver driver = new InternetExplorerDriver();
What is the 'select' command in selenium? How to handle drop down?
The 'select' command allows you to pick a value from a dropdown as long as the property is in the 'select' tag name on a web page. In order to use 'select', we should store the web element using findElement as a WebElement variable. Then we can select the element by visible text, value, or index.
What is the Page object model? What is the page object model framework in Selenium WebDriver?
The Page Object Model (POM) is a design pattern in Selenium that creates an object repository for storing web elements. It's used to enhance automation framework robustness and maintainability. In POM, each web page has its own Java class, containing web elements and methods specific to that page. This structure simplifies maintenance, promotes code reusability, and improves script readability and reliability. The process involves: 1. Creating class files for each web page. 2. Implementing a base class. 3. Defining constructors and utilizing TestNG annotations. 4. Declaring variables for web elements and corresponding methods.
What is the Selenium WebDriver in Java?
The Selenium WebDriver allows us to perform web testing using different browsers such as Firefox, Internet Explorer, Safari, and Chrome. WebDriver is a built-in Selenium command which allows us to define and use a specific browser. In Selenium, the keyword "WebDriver" represents a web browser.
What is the super interface of WebDriver?
The WebDriver interface in Selenium has several super interfaces, including: SearchContext: Used to locate elements on a web page. JavaScriptExecutor: Provides methods to execute JavaScript code in the browser. TakesScreenshot: Implemented by classes that capture and save screenshots of web pages
What is the WebElement command
The WebElement command allows you to store a locator like id, class, xpath, etc. from a webpage into a user-defined variable.
What does the List<WebElement> command allow you to do?
This command allows you to store multiple webelements in a list
What is the difference between using Thread.sleep and implicit wait or explicit wait?
Thread.sleep is a general Java method that pauses code execution for a specified time in milliseconds. It doesn't consider the state of web elements, and you must manually define the sleep duration. Using Thread.sleep can lead to unnecessary delays and less efficient test execution. Implicit Wait, a Selenium feature, instructs the WebDriver to wait for a set amount of time before raising a "No Such Element Exception." This wait is applied globally to all web elements, providing a basic level of synchronization. While it avoids excessive waiting, it may still lead to inefficiencies as it waits for the same duration for all elements. Explicit Wait, also part of Selenium, offers more precise control. It waits for a specified condition to be met before proceeding. This allows you to target specific elements, making your tests more efficient and responsive. Explicit waits are preferable when you want to synchronize with the dynamic behavior of web elements. In summary, while Thread.sleep ca
How do you handle tabs in selenium?
To handle two or more tabs, we need to use ArrayList<String> with the getWindowHandles() command. This will store all currently open tabs in an arraylist, and we can switch to which tab we want by indexing the arraylist.
How to run your tests on different browsers?
To run tests on different browsers, tests can be executed using Selenium with 3rd-party drivers designed for popular browsers like Mozilla, Chrome, and IE. First, ensure that the necessary driver files are downloaded for the system. To execute the same tests on different browsers, parameterized testing via TestNG XML can be employed. By passing different browser parameters to the test scripts, various browsers can be sequentially invoked for testing. In Cucumber, a similar outcome can be achieved using Cucumber data tables to pass different browser values to step definitions and conduct tests across multiple browsers.
How do you setup a Selenium environment?
To set up a Selenium environment, we first need to install a JDK for writing scripts in Java and use Eclipse as an editor to write code. Once the Java environment is setup, we can directly use the Selenium jars in a Java project or through a Maven project by installing Selenium dependencies in the pom.xml file from the Maven central repository.
How do you locate an element using selenium?
Using a driver.findElement(By.xpath...
How do we click on a hyperlink using linkText?
We can only use linkText on links. All hyperlinks can be identified using linkText.- The text in between the anchor tags is used as the linkText- Locate the element using findElement() and linkText, and then use the click method.
How to find web elements?
We can use the Chrome developer tool or any other browser's developer tools to find the element. Developer tools let us inspect the web elements' code, and we can find different attributes and their values in the code. Selenium supports multiple attributes that include id, name, xpath, and CSS selector.
How can I capture a property value from an element? Hint: not getText it is another method similar to that
We can use the getAttribute() method. It returns the value of the attribute of a web element. It's used when we need to verify the text on an input field, or field dimensions, etc. We need to give it the web element, and the attribute name, and it will return the value of that attribute in that web element.
How do you get a current url from a page? hint: you can store the url in a variable and let say if you want to re navigate to that specific url then you can just pass the variable on your navigate command
We can use the getCurrentUrl() method to get the current url from a page. So if we want to renavigate to that page, we can just store the url in a variable, and pass the variable on the navigate method.
How do you perform any type of mouse movement in selenium?
We need to define the mouse movement using the 'Actions' command, which is: Actions actions = new Actions(driver); We can then use 'Actions' to perform any type of mouse movement, such as: clicking on an element: actions.moveToElement(element).click().perform(); entering input: actions.moveToElement(element).sendKeys("xyz").perform(); or hovering over an element: actions.moveToElement(element).perform(); This becomes useful when you need to hover the mouse over an element to open a dropdown menu.
How do you synchronize your Selenium code with your browser?
We use wait statements, implicit and explicit wait. Selenium is faster than the browser, so we use the wait statements to synchronize selenium with the browser.
How can you handle windows based pop up?
We would use the getWindowHandle() method to store the window ids, then switch to a particular window using driver.switchTo().window(), and then close it.
What is the command to use the chromedriver in selenium without having to manually download it?
WebDriverManager.chromedriver().setup();
When do you use xpath?
When an element doesn't have an id or name property, and a class name might not be unique, we use xpath to identify any additional unique properties of the web element.
Action Class Methods/Features
a set of different actions with a common but unique set of features: Click(): Simply clicks on the element DoubleClick(): Double clicks on a particular locations ContextClick(: Performs right click operation ClickAndHold(: Clicks at the current mouse location without releasing it DragAndDrop): invokes ClickAndHold at source location moves to the target without releasing the mouse DragAndDropBy0: It performs ClickAndHold at the source location and shifts according to the given offset horizontally or vertically (X and Y axis) MoveByOffset(): Helps in shifting the mouse from current position to the given offset MoveToElement(): Helps to shift the mouse location to the centre of the page MoveByOffset): Helps in shifting the mouse from current position to the given offset MoveToElement(): This method helps in shifting the mouse to the centre of the element Release() : Helps release the left mouse button
What is the difference between the click() and submit() actions?
click() is for clicking on an element, while submit() acts as an 'enter' key. Because when you use submit(), sometimes the clicking doesn't work when there's a popup blocking the element to click on, so submit() is like hitting the 'enter' key on your keyboard.
How do I click on a link?
driver.findElement(By.Xpath(......)).click();
How do I check if an element is displayed or not?
driver.findElement(By.Xpath(......)).isDisplayed(); (If the element is not displayed, It will throw an exception, and we have to use the try-catch block to handle the exception.) In the try, we can use "return true" and in the catch, we can use "return false".
How do I check if the checkbox is selected or not?
driver.findElement(By.Xpath(......)).isSelected(); (If the element is not selected, It will throw an exception and we have to use try catch block to handle the exception). In the try, we can use "return true" and in the catch we can use "return false". ----or---- driver.findElement(By.Xpath(......)).getAttribute(class).contains("checked");
How do I write data in a text box?
driver.findElement(By.xpath(......)).sendkeys("........");
How do you make sure that you have enough links in a webpage?
driver.findElements(By.tagName("//a")).size(); (all the links in a webpage starts with an Anchor Tag. By using above command, we can get all the links present in the webpage).
What is the syntax code for delete all cookies?
driver.manage().deleteAllCookies();
What is the syntax for implicit wait in selenium?
driver.manage().timeouts().implicitlyWait(4,TimeUnit.SECONDS);
What is the difference between driver.close() and driver.quit() ?
driver.quit() is used to exit the browser, end the session, tabs, pop-ups, etc. But when you use driver. close(), only the window that has focus is closed.
What is the difference between findElement() and findElements()?
findElement() locates an element by its property and value. findElements() locates an array of elements where some elements have the same exact class, properties, and values. Therefore, we have to specify an element of the same group by using an index, starting from 0. findElements allows you to locate an element by index number if multiple links have the same exact tag name and same properties. If I want to click on the first element of a list with the same properties, I can use index 0 and the findElements & get() command. Example: driver.findElements(By.className("options")).get(0).click();
How do you use more than one property in an xpath?
place the xpaths side by side: "//tagname[@property1='value1'] [@property2='value2']" Or you can use the logical operands (and/or): Ex: "//tagname[@property1='value1' and @property2='value2']"
Which web element always has a unique value?
the ID web element
How can I verify if a checkbox is selected or not?
use the isSelected() method over the checkbox element. It returns a boolean value of true if the checkbox is checked, and false otherwise.