Friday, 17 October 2014

Few useful Commands in Selenium Webdriver

Open Browser
WebDriver driver = new FirefoxDriver();
For other browser and details are discussed in my earlier blog. Please have a look here.

Open Page URL
Get” method is used to open a particular url in browser.
driver.get("https://www.gmail.com");

Passing values in text field
sendKeys” keyword is used to enter values to the field.
driver.findElement(By.id("Email")).sendKeys("testuser@gmail.com");


Clear value from Text field
clear() method is used to clear the field.
driver.findElement(By.id("Email")).clear();

Clicking button
Here click() method is used to click a button.
driver.findElement(By.id("signIn")).click();


Submit button
In the above case, Sign in is a button. But works as a submit button too. So, below code will work as well.
driver.findElement(By.id("signIn")).submit();

Selecting value from drop-down
We have 3 different methods to select the drop-down value.
selectByIndex() → Here index is the order in drop-down, and 1st element is always having index 0.
selectByVisibleText() → It is the visible text , what we see in drop-down list and want to select.
selectByValue() → It is the option value, which can be viewed in Firebug inspector

Look at these option values, we got through Firebug inspector for that particular dropdown.

<option value="">Select Country</option>
<option value="111">Denmark</option>
<option value="120">Sweden</option>
<option value="127">Normay</option>
<option value="139">Germany</option>
<option value="143">Paris</option>
<option value="219">Austria</option>
<option value="224">Spain</option>


Let see an example here of selecting value by 3 ways.

Select selectBox = new Select(driver.findElement(By.id("Country")); // Here dropdown field is clicked
selectBox.selectByIndex(0); // Select through Index
“OR”
selectBox.selectByVisibleText(“Denmark”); //Select through visible Text
“OR”
selectBox.selectByValue(111); //Select through option value

Deselecting value from drop-down
Here also we have 3 different methods to select the drop-down value.
deselectByIndex() → Here index is the order in drop-down, and 1st element is always having index 0.
deselectByVisibleText() → It is the visible text , what we see in drop-down list and want to select.
deselectByValue() → It is the option value, which can be viewed in Firebug inspector

Here command is also almost same as selecting drop-down.
selectBox.deselectByIndex(0); // Deselect through Index
“OR”
selectBox.deselectByVisibleText(“Denmark”); //Deselect through visible Text
“OR”
selectBox.deselectByValue(111); //Deselect through option value

Selecting/Deselecting Check box
Here click() method is used to toggle on/off for checkbox.
driver.findElement(By.id("PersistentCookie")).click();


Selecting Radio button
Here also, it will work in same way of checkbox.
driver.findElement(By.id("Ad_Type_1")).click();

Accepting a Confirm box
driver.findElement(By.id(("Delete_Ad"))).click(); // Here the Alert window is opened on clicking   button
Alert alert = driver.switchTo().alert(); 
alert.accept(); // This line is to accept the alert box, means clicking Ok.


For Alert and Prompt boxes also, It will work in same way.

Rejecting a Confirm box
Here, also it will work in same way as of Accepting confirm box.
driver.findElement(By.id(("Delete_Ad"))).click(); // Here the Alert window is opened on clicking   button
Alert alert = driver.switchTo().alert();
alert.dismiss();  // This line is to click 'Cancel' in the confirm box.

For Prompt boxes also, it will work in same way.
And in Alert box, we don't have cancel button to reject.

Maximize screen
Here is the command to maximize the brower window.
driver.manage().window().maximize();

Navigate
Here are few commands related to navigation.
driver.navigate().to("http://thetestzing.blogspot.in//2014/10/locating-web-elements-in-selenium.html"); // Here it will navigate to the particular page.
driver.navigate().back(); // Here it is same as clicking browser back button
driver.navigate().forward(); // Here it is same as clicking browser forward button
driver.navigate().refresh(); // Here it is same as refreshing/reloading the browser page.

Verify Element
Sometimes in our application, we may need some verification. Like after logging into a site, we can verify whether the login name present or not and we can confirm that correct user is logged in.

Lets see the example below.

WebElement Element = driver.findElement(By.xpath("//*[@id='Text1']/div[1]/span"));

Boolean iselementpresent = Element.isEnabled();
if (iselementpresent == true) {
System.out.println("Text is--"+ Element.getText());
}
else{
System.out.println("Element not found");
}
Here in the 1st line we found the xpath for a text element and stored that path in a web element.
Then created one boolean object which will accept true or false value.
Then in If-Else block we compared that boolean value. If it is true, then it will print that text, else will print the message mentioned.

Sunday, 12 October 2014

Selenium Webdriver commands to Initialize Browser like Firefox, Safari, IE, Opera and Run

Command for Firefox/Safari driver

In my earlier blogs we have already used some commands to initialize the firefox driver.
Here is the command to initialize Firefox driver.
WebDriver driver = new FirefoxDriver();

For Safari also, we don't need to do much things. There also single line coding will work. But will work good with Mac Osx. Here is the command for safari browser.
WebDriver driver = new SafariDriver();

Like we did for Firefox/Safari driver, same will not work directly for other browsers like Chrome, Opera, Internet Explorer etc. We need few additional stuffs there.

We need to download the driver files first for other browsers. Lets start with IE browser first.

Steps and command for IE driver

Step 1: Go to this URL http://www.seleniumhq.org/download/
Step 2: Go to “The Internet Explorer Driver Server” section.


Step 3: Now you can download the IE driver zip file of 32 or 64 bit as per requirement.
Step 4: Extract the zip file and save the 'IEDriverServer.exe' in a proper place (say here: C:\\Users\\debasisa\\Desktop\\IEDriverServer.exe )


Now, here is the code to initialize the IE driver:

public static void main(String[] args){

File file = new File("C:\\Users\\debasisa\\Desktop\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("Testuser");
driver.findElement(By.id("Passwd")).sendKeys("Testpassword");
driver.findElement(By.id("signIn")).click();

driver.close();
driver.quit();

}


Explanation:
1. In first line, we created file object which holds the path for the IE driver.
2. In 2nd line, we set the property, so that Webdriver can access that path.
3. In 3rd line we initialize the IE driver.
4. Now Gmail instance is opened in IE browser. Then located the Email/Password fields through locator 'id'. Then though 'sendKeys', we entered values to Email/password fields and clicked on “SignIn” button. After that closed the IE browser.

*Note:
It will not work on all versions on IE. Supported versions are from IE 6 to IE 11, where as for Version 11, we need some additional settings in Registry file.


Steps for Additional setting to run in IE11:

Step 1: Go to Start menu of Windows system, click Run and type 'REGEDIT'
Step 2: It will open registry edit window.
Step 3: There go to the below folder path.

For 64 bit machine HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\InternetExplorer\Main\FeatureControl\
FEATURE_BFCACHE

For 32 bit machine
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\InternetExplorer\Main\FeatureControl\FEATURE_BFCACHE

The last folder mentioned 'FEATURE_BFCACHE' might not present there. So, create a new Key there with this name.



Step 4: Now in that 'FEATURE_BFCACHE' folder, create a 'DWORD' with name: 'iexplore.exe' & value 0 .



Step 5: Now we are all set. We can run our same piece of code in Eclipse, it will work in IE 11 as well.


*Note:
But running code in IE 11 is bit slower. Through sendkeys when we pass values like Email/Password etc., we can see that it will type very slowly. And it is because of 64bit driver.

Try using 32 bit IE driver file. Though it is not much compatible with Win 64 bit system, but this slow responsiveness issue can be resolved by this 32 bit IE driver server.

We need all these additional settings, because IE driver server doesn't support directly for IE 11.
But currently IE 11 driver server is available to download, but that is for Win8.
If you are on Win8, it is worth trying.
You can download IE 11 driver server from here.


Steps and command for Chrome driver

Step 1: Go to this URL http://www.seleniumhq.org/download/
Step 2: Go to “Third Party Drivers, Bindings, and Plugins” section.



Step 3: Click on the version no. and then choose the link as per need like Win/Mac/Linux etc. And then download the zip file.
Step4: Extract and save the “chromedriver.exe” file in a proper place (say here: C:\\Users\\debasisa\\Desktop\\chromedriver.exe )


Now, here is the code to initialize the Chrome driver:

public static void main(String[] args){

File file = new File("C:\\Users\\debasisa\\Desktop\\chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("Testuser");
driver.findElement(By.id("Passwd")).sendKeys("Testpassword");
driver.findElement(By.id("signIn")).click();

driver.close();
driver.quit();

}

Explanation:
1. In first line, we created file object which holds the path for the Chrome driver. 
2. In 2nd line, we set the property, so that Webdriver can access that path.
3. In 3rd line we initialize the Chrome driver.
4. Now Gmail instance is opened in Chrome browser. Then located the Email/Password fields through locator 'id'. Then though 'sendKeys', we entered values to Email/password fields and clicked on “SignIn” button. After that closed the chrome browser.




Steps and command for Opera driver
Like we downloaded the driver file for Chrome, we can download the opera driver file in the same way.

But here after extract, we will get a .jar file. We need to add that jar file to build path.
Here are the steps below.

Step 1: Go to this URL http://www.seleniumhq.org/download/
Step 2: Go to “Third Party Drivers, Bindings, and Plugins” section.

Step 3: Click on the version no. to download. Here, it will download the .jar file, rather than .exe file.
Step 4: Now, we need to add that jar file to the build path of our project in Eclipse.
Here are the steps mentioned below to add the jar file.

Open Eclipse → Go to Project → Right click → Build Path → Configure Build Path → Add External JARs → Then select the downloaded Opera driver jar file → Click Ok to save that

After adding jar file in build path, we can view the same.

                             


Step 5: Now copy the path of 'opera.exe' file. It is the launcher file, what we got after installation of opera browser, mostly the location is in program files. 

Say the path is: “C:\\Program Files (x86)\\Opera\\opera.exe” .

Now here is the code to initialize opera driver and run the program in opera browser.



public static void main(String[] args){

File file= new File("C:\\Program Files (x86)\\Opera\\opera.exe");
System.setProperty("webdriver.opera.driver", file.getAbsolutePath());
WebDriver driver = new OperaDriver();

driver.get("https://www.gmail.com");
driver.findElement(By.id("Email")).sendKeys("Testuser");
driver.findElement(By.id("Passwd")).sendKeys("Testpassword");
driver.findElement(By.id("signIn")).click();

driver.close();
driver.quit();

}

Explanation:

1. In first line, we created file object which holds the path for the Opera browser. Here it is the path of 'opera.exe' which we saved in step 5 above.
2. In 2nd line, we set the property, so that Webdriver can access that path.
3. In 3rd line we initialize the Opera driver.
4. Now Gmail instance is opened in Opera browser. Then located the Email/Password fields through locator 'id'. Then though 'sendKeys', we entered values to Email/password fields and clicked on “SignIn” button. After that closed the opera browser.


*Note:
It will work only for opera versions 12.x or lower than that. For higher versions of opera, it won't work.


Sunday, 5 October 2014

Locating Web Elements in Selenium Webdriver PART 3

Locate Elements By CSS Selectors in Selenium Webdriver

Till now we have covered locating elements through Id and Xpath in my earlier blogs. Now lets get into for cssSelector. The way of finding css selector is almost same as xpath.

Lets consider the same piece of html code which we found through Firebug for Email field of Gmail.
<input id="Email" class="" type="email" spellcheck="false" value="" placeholder="Email" name="Email">
Here we can write css like: “input[id='Email']

So, the code will look like below.
driver.findElement(By.cssSelector("input[id='Email']"));

So, this is the manual way to write css. But there are several ways to get css as well.

Steps to Find CssSelector:
Step 1: Install Firepath, which is an Add-on for firefox browser.
Step 2: Open the testing site in Firefox (say we have opened “https:// www.gmail.com”)
Step 3: Lauch Firebug, go to Firepath tab, then from drop-down select css and start inspecting elements.
Step 4: Move mouse to the field/button/link for which you want to locate, then click (say 'Email' field)
Step 5: In Firepath, we can see the css for that particular field.

See the screen shot below.

Here we found css as “#Email

Now our piece of code will look like below.
driver.findElement(By.cssSelector("#Email"));

Apart from this, we have some other way of finding css path. Like in my 
earlier blog, we saw for xpath. In same way, we can find for css path as well.
Through firebug, after inspecting element, we can right click there, it will show to copy css path there.
See screen shot below.

Also through Selenium IDE also, after recording, we can view the target. There also we can find the css path as well.
See screen shot below.




Now let see the code to Enter Email/Password and click submit button in Gmail using cssSelector.

Public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.get("https://www.gmail.com/");
driver.findElement(By.cssSelector("#Email")).sendKeys("Testuser");
driver.findElement(By.cssSelector ("#Passwd")).sendKeys("Testpassword");
driver.findElement(By.cssSelector ("#signIn")).click();
driver.close();
driver.quit();

}

In the above code, we opened Gmail sign in page in Firefox browser.

Then located the Email/Password fields through locator 'cssSelector'.
Then though 'sendKeys', we entered values to Email/password fields and clicked on “SignIn” button. After that closed the browser.

Some other locators: name, className, linkText

Consider one example: Open Gmail sign in page, there below Sign in button, 
we have a link “Need help?”Now through firebug, inspect this element.

See the below screen shot and look at the html content, there we can see the class name, link name, Id etc.


Now we will locate that link “Need help?” through className & linkText.

Through class name: 
driver.findElement(By.className("need-help-reverse")).click();

Through Link text:
driver.findElement(By.linkText("Need help?")).click();

It is all about locators. Apart from that some other locators are there, but they are not so famous as most of the web elements can be located using all these locators, we studied.
All these locators can also be found in other browsers as well.