Selenium WebDriver FAQs


1. How to handle proxy authentication popup?
Install AutoAuth addon in Firefox

2. How to use specific Firefox profile in Selenium WebDriver?

ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
WebDriver driver = new FirefoxDriver(ffprofile);
String URL = "http://www..google.com/";


3. What are available addons for xpath identification in Firefox?

FireBug - Using this add-on, you can edit, debug, and monitor CSS, HTML in any web page.
FirePath - is a Firebug extension that adds a development tool to edit, inspect and generate XPath expressions, CSS selectors and JQuery selectors
XPath Checker - An interactive editor for XPath expressions. Choose 'View XPath' in the context menu and it will show the editor.
WebDriver Element Locator - This is one of the important add-on. This addon is designed to support and speed up the creation of WebDriver scripts by easing the location of web elements.
Firefinder -  Find elements matching one or several CSS expressions, or an XPath filter

4. How to set object identification timeout in Selenium WebDriver? (or) How to avoid NoSuchElementFound exception? (or) How to set implicit wait in Selenium WebDriver?

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 

5. How to setup proxy in eclipse to install new plug-ins? (or) I am trying to download a plug in from a site, but it won't connect, it keeps saying "Pending" (or) connecting to eclipse via proxy

Window->Preferences
General-> Network Connection
Select Active Provider as Manual
Set HTTP/HTTPS proxy along with proxy IP, Port, Authentication(User/Password)
**Imp** Clear SOCKS proxy if this is set i.e. select SOCKS proxy row and click on Clear button
Restart Eclipse

6. How to open internal web browser in Eclipse?
Window -> Show View -> Other -> General -> Internal Web Browser

7. How to read a property file in Selenium/Java?

import java.util.Properties;

//Method to read property file
public Properties readPropertyFile(String file){
     
      Properties property = new Properties();
      try{
          property.load(new FileInputStream("envfile.txt"));
          System.out.println("Property file loaded successfully");
      }
      catch(FileNotFoundException e){
          System.out.println("File:="+file+" not found");
      }
      catch(IOException e){
          System.out.println("File:="+file+" is not readable");
      }
     
      return property;
  } 


Code to call above method and read a property from envfile.txt:

property=readPropertyFile("envfile.txt");
property.getProperty("url") 

8. How to view height and width of an element using Firebug in Firefox browser?

















 9. How to get x and y coordinates of an element?
int x=driver.findElement(By.name("userName")).getLocation().x;
int y=driver.findElement(By.name("userName")).getLocation().y;

In above code, getLocation() will return Point object, this holds x and y values.

10

Create an testng.xml file say name as testsuite.xml.
Now follow below 2 steps:
Step 1: Create an batch file for scheduler:
use below code - modify it and paste in notepad. save the notepad in working directory as"run.bat"
set ProjectPath=C:\Selenium\Selenium_tests\DemoProject 
echo %ProjectPath%
set classpath=%ProjectPath%\bin;%ProjectPath%\Lib\*
echo %classpath%
java org.testng.TestNG %ProjectPath%\testsuite.xml
a) First line is for setting project path b) second line is for verifying that path is set or not. c) third line is for setting classpath - lib folder contain all the jar file added to project build path d) fourth line is for verifying whether classpath is set or not e) fifth line is for executing xml file having details of all test.
Step 2: go to control panel > administrative tool >task scheduler and create a task which will trigger run.bat file at the time you want.
it will work.

11. How to install Cucumber plug-in in eclipse?
Use below URL to install cucumber plug-in in eclipse
http://cucumber.github.com/cucumber-eclipse/update-site

12. How to perform scroll operation in Selenium? 
         Long clientH,pageH,temp;
        driver.get("www.test.com");       
        JavascriptExecutor js=(JavascriptExecutor)driver;
        pageH=(Long)js.executeScript("return document.documentElement.scrollHeight");
        clientH=(Long)js.executeScript("return document.documentElement.clientHeight");       
        temp=clientH;
       
        while(temp<=pageH){
            js.executeScript("document.documentElement.scrollTo(0,"+temp+")");
            temp=temp+clientH;
            Thread.sleep(3000);
        }

13. How to create Maven Selenium project?
Open Eclipse
Select File->New->Maven->Maven Project
Check the checkbox -"Create a simple project"
Enter GroupID and ArtifactID
GroupID - It's domain/company name. For example, Fusion e.t.c
ArtifactID - It is the name of the jar without version number. It's your project name. For example, Financials or Payables e.t.c

14. How to handle "Authentication Required" popup in Firefox?
You need to create AutoIT script with below code

WinWaitActive("Authentication Required","","60")
If WinExists("Authentication Required") Then
   Send("user{TAB}")
   Send("password{ENTER}")
EndIf

15. How to get window title? (or) How to get browser title? or How to assert browser title?
Assert.assertEquals("Google", driver.getTitle());

16. How to convert existing Java project to Maven project?
Right click on Java project -> Configure -> Convert to Maven project

17. How to use following-sibling in XPath?
For example, consider below HTML source code.

<div class="ms-tableRow" id="ct_00_ProfileViewer_Manager">
<span class="ms-soften ms-tableCell ms-profile-detailsName ">Manager</span>
<span class="ms-tableCell ms-profile-detailsValue">
<a href="http://www.tr.com/800393">John</a>
</span>
</div>

In this page, you want to capture Manager's name, then the XPath would be as below
Method1: 
//span[text()='Manager']/following-sibling::span/a

Method2: 
//div[contains(@id,'ProfileViewer_Manager')]/span[@class='ms-tableCell ms-profile-detailsValue']/a

18. How to write AutoIT script for upload functionality?
Sleep(5000)
WinWaitActive("File Upload","","180")
If WinExists("File Upload") Then
   ControlSetText("File Upload","","Edit1","D:\Automation\Resources\pic.jpg")
   ControlClick("File Upload","","Button1")
EndIf

19. How to call AutoIT script from a Selenium test?
Create .exe for the AutoIT script and then use below line of code to call AutoIT script.
Runtime.getRuntime().exec("D:\\Automation\\Autoit\\FF_Authentication.exe");


20. How to switch to frame object and then switch back to Parent object?
//Store Parent's window handle in a variable
String temp=driver.getWindowHandle();

//Switch to frame object and then do whatever you want
driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@id,'DlgFrame')]")));

//Switch back to parent window
driver.switchTo().window(temp);

21. How to get parent node?

//h4[text()='Tickets & Reservations ']/parent::div
(or)
//h4[text()='Tickets & Reservations ']/parent::*
(or)
//h4[text()='Tickets & Reservations ']/..

22. Axes


22. How to find an element using index? 

driver.findElement(By.xpath("//div[2]"))

23. How to use partial attribute match in XPath? (or) How to handle object identification of dynamic objects using XPath ?

Method1: //a[starts-with(text(),'Gma')]

Method2:
//a[contains(@id,'gb_')]

Method3: [**Note: This will work only in XPath2.0 supported browsers]
//a[ends-wth(@id,'search')]

24. How to escape single quote( i.e. ' ) or apostrophe in XPath? 

Try identifying I'm Feeling Lucky button in Google search page.
You can use double quotes in XPath when attribute has an apostrophe (or) single quote.
//input[@value="I'm Feeling Lucky"]

25. How to verify an element is NOT present on a web page?
This can be verified in many ways.

Method1: Write a reusable function with below code.

try{
            driver.findElement(By.xpath("//input[@id='txtId']"));
            return true;
}
catch(NoSuchElementException e){
            return false;
}


Method2: Use wait and expected conditions. Below code should be in appropriate try-catch block with return type.
WebDriverWait wait=new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.numberOfElementsToBe(By.xpath("//th[text()='Id']"), 0));

26. Different kinds of exceptions encountered in Selenium WebDriver?
UnreachableBrowserException:
org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died. This exception occurs when the browser window closed during execution

org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up. The most frequent cause of this is that page that the element was part of has been refreshed, or the user has navigated away to another page.

27. How to read HTML table  (or) Web Table using Selenium WebDriver?
This is not always very simple. Below is a typical way of reading data from Web Table

//Get the table rows
List<WebElement> rows=driver.findElements(By.xpath("//table[@id='Offerings']/tbody/tr"));

System.out.println("No.of rows in the table:="+rows.size());
       
        //Iterate all rows to print the data
        for(WebElement row:rows){
           
            //Get the cells
            List<WebElement> cells=row.findElements(By.tagName("td"));
            System.out.println("Total cells in the row:="+cells.size());
           
            //Iterate all cells to print the data
            for(WebElement cell:cells){
                System.out.print(cell.getText()+" , ");
            }
            System.out.println("");
        }


28. How to switch the control to new window?
Use below code to switch to latest window.
for(String window : driver.getWindowHandles()){
           driver.switchTo().window(window);           
}  



29. How to perform mouse hover operation in Selenium WebDriver?
WebElement e=driver.findElement(By.xpath("//div[@id='nav-subnav']/a[7]/span"));
Actions action = new Actions(driver);
action.moveToElement(e).perform();



30. Selenium WebDriver code is getting hanged after clicking on a link which opens a new browser popup? 
(or)
Unable to handle newly opened grand child window from a child window
(or)
How to handle modal window/popup using Selenium WebDriver? 
(or)
Getting "Thread [Forwarding findElement on session 38d5978e-ec0b-412c-ad18-af2f3839da9c to remote] (Stepping)" message in debug window after Modal window is opened.



I have encountered this problem as part of pilot project. Once such window or popup is opened, it will block its parent window and whatever the code which you have written after this modal popup will not be executed.



We need to use multi threading concept as below to handle this scenario.



import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.internal.ProfilesIni;

public class Test implements Runnable{
    public static WebDriver driver;
    Thread thread;   
    Test() throws InterruptedException{       
        thread=new Thread(this,"test");
        thread.start();
    }

    public void run(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
        //Switch to pop-up
        for (String handle : driver.getWindowHandles()) {           
            driver.switchTo().window(handle);
        }
       
        //Print pop-up Handle
        String nextHandle = driver.getWindowHandle();
        System.out.println("nextHnadle" + nextHandle);
       
        driver.findElement(By.xpath("html/body/input[2]")).click();
       
        //Switch to pop-up
        for (String handle : driver.getWindowHandles()) {           
            driver.switchTo().window(handle);
        }
        driver.switchTo().alert().accept();
    }
    public static void main(String args[]) throws InterruptedException{

        ProfilesIni p=new ProfilesIni();

        driver=new FirefoxDriver(p.getProfile("default"));
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.get("https://developer.mozilla.org/samples/domref/showModalDialog.html");
        new Test();
        driver.findElement(By.xpath("html/body/input")).click();
       
       

    }

}
 
31. How to get innerHTML of an element? (or) How to read CDATA content from XML?
System.out.print(driver.findElement(By.xpath("//inputDoc")).getAttribute("innerHTML"));

32. How to know whether page is fully loaded or not? (or) How to wait for page load?
We need to make use of javascript snippet to know whether page is loaded fully or not.

JavascriptExecutor je=(JavascriptExecutor)driver;
System.out.print(je.executeScript("return document.readyState"));


document.readyState will return either interactive or loading (i.e. when page is still loading) or complete (i.e. when page loading is completed) depending upon page loading status.

33. How to get the URL of current browser using WebDriver?
driver.getCurrentUrl() 

34. How to know whether an element is enabled or not?
boolean f=driver.findElement(By.xpath("//input[@name='textfield']")).isEnabled(); 

35. How to capture alert message? (or) How to accept alert message?
System.out.println(driver.switchTo().alert().getText());
driver.switchTo().alert().accept();


36. How to capture screenshot and store it in a file?
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

import org.apache.commons.io.FileUtils;
File a=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(a, new File("b.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


37. How to set download directory in Firefox?
ProfilesIni p=new ProfilesIni();FirefoxProfile newProfile=p.getProfile("default");
newProfile.setPreference("browser.download.folderList", 2);
newProfile.setPreference("browser.download.dir","D:\\Downloads");
driver=new FirefoxDriver(newProfile);

38. How to launch Chrome browser?
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\Tools\\chromedriver.exe");
driver=new ChromeDriver();


39. How to convert back Maven project to Java project?
Select the project in 'Package Explorer'
Right click on it
Select 'Maven'->'Disable Maven Nature


40. Getting Failed to connect to binary FirefoxBinary error when executing Selenium test?
This should be mostly with Selenium WebDriver version. Try upgrading latest Selenium version to avoid this exception.

41. How to perform drag and drop using Selenium WebDriver?
FirefoxDriver driver=new FirefoxDriver();
driver.get("http://testing.com/drag-and-drop.html");
WebElement source=driver.findElement(By.xpath("//div[@id='abc']"));
WebElement target=driver.findElement(By.xpath("//div[@id='xyz']"));       
Actions actions=new Actions(driver);
actions.dragAndDrop(source, target).build().perform();


42. How to get entire Page source (or) raw HTML content? 
System.out.print(driver.getPageSource());

//
43. "Some projects cannot be imported because they already exist in the workspace" error when trying to import  existing project in Eclipse?
Uncheck 'Copy projects into workspace' option in 'Import Projects' popup. Then you will be able to import existing project into workspace.

44. What is JAVA_HOME?
C:\Program Files (x86)\Java\jdk1.8.0_77 

45. How to uninstall Jenkins or How to clean Jenkins workspace or How to upgrade from one version of Jenkins to other version?
Go to C:\Users\<User>\.jenkins directory and delete this directory. Then try upgrading to newer version. Please note that this step will delete your existing builds and projects from Jenkins. Use this option with caution.

46. How to update Maven project after adding a new dependency?
Right click on Project -> Maven -> Update Project 

47. How to search for an element(s) within an WebElement?
So, given some sub-node, "x", the XPath:

//y

... will still find any node, "y", located anywhere within the XML tree. But, the XPath:

.//y

... will find any node, "y", that is a descendant of the node "x." In other words, preceding the "//" expression with a "." tells the XML search engine to execute the search relative to the current node reference.


48. How to run multiple test suites using single TestNG xml file?
Create a TestNG xml file as below. Add list of suites which you want to execute  under <suite-files> tag.

<suite name="allSuites">
  <suite-files>
    <suite-file path="suite1.xml" />
    <suite-file path="suite2.xml" />

..........
...........
  </suite-files>
</suite>


49. Selenium IE11 Driver issue

  • For IE 11 only, you will need to set a registry entry on the target computer so that the driver can maintain a connection to the instance of Internet Explorer it creates. For 32-bit Windows installations, the key you must examine in the registry editor is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. For 64-bit Windows installations, the key is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BFCACHE. Please note that the FEATURE_BFCACHE subkey may or may not be present, and should be created if it is not present. Important: Inside this key, create a DWORD value named iexplore.exe with the value of 0.

No comments:

Post a Comment