Thursday, 6 November 2014

Selenium Web driver in Java tutorial

CSS Selector examples in selenium webdriver


Below table shows commonly used css Selectors in Selenium.


Find all elements with tag input

input
Find all input tag element having  attribute type = ‘hidden’
input[type='hidden']
Find all input tag element having  attribute type = ‘hidden’  and name attribute = ‘ren’
input[type='hidden'][name='ren']
Find all input tag element with attribute type containing ‘hid’
input[type*='hid']
Find all input tag element with attribute type starting with ‘hid’
input[type^='hid']
Find all input tag element with attribute type ending with ‘den’
input[type$='den']

Below example demonstrates how we can use cssSelectors to identify the elements in Java.
To identify the edit box with name attribute as q, we can use below css expression.
input[name='q']
Above css Selector expression will identify the element with tagname as input and of which name attribute’s value is name.


//find element having name attribute as q using css
           driver.findElement(By.cssSelector("input[name='q']")).sendKeys("css");

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Monday, 3 November 2014

Unable to select value from drop down in selenium webdriver.

Sometimes you may encounter a scenario where selenium Select class can not be used to select the value from the drop down or list box in any browser like internet explorer, google chrome or firefox.
Sometime situation is more difficult because after selecting the value from drop down, other controls on the page get auto populated.
So basically there are 2 problems.
  1. Selenium unable to select the value from the drop down.
  2. Java script event does not get invoked. So other controls do not get auto populated.
We can solve above issues by below code.

WebElement c = driver.findElement(By.xpath("//select[@name='empType']"));
((JavascriptExecutor) driver).executeScript("arguments[0].value='X';",c);

Above script will select value X from the drop down.

After this you will have to trigger the on change event on the drop down using below code.

((JavascriptExecutor) driver).executeScript(
"var evt = document.createEvent('HTMLEvents');
evt.initEvent ('change', true, true);
arguments[0].dispatchEvent(evt);",c);


This will fire the drop down change event on the web list.
What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday, 1 November 2014

How to use TestNG with Selenium Webdriver?

TestNG is the next generation testing framework. You can easily integrate your selenium scripts in TestNG.

Please follow below steps to run TestNG tests in Eclipse.

  1. Download TestNG at http://testng.org/doc/download.html
  2. Then Create a TestNG class in any project.
  3. Define test methods in that class using @Test annotation
  4. Right click on the TestNG class and run as TestNG class.
In below example, we have created a TestNG class called NewTest with 2 test methods Test1 and Test2.

package framework;

import org.testng.Assert;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class NewTest {
  @Test
  public void Test1() {

   //Test something here.
   Assert.assertNotNull("abc");
  }
  
  @Test
  public void Test2() {
   //Test something here.
Assert.assertNull("jj"); } @BeforeSuite public void beforeSuite(){
      //this method is called once before test execution starts
//here you can write a code to launch the selenium web driver. } @AfterSuite public void afterSuite(){
      //this method is called once after test execution ends.
//here you can write a code to close and quit the selenium web driver. } }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com 

How to upload files in selenium web driver using AutoIT Script?

Some times you will have to handle the file upload window using selenium web driver.
Selenium does not provide any such way to handle the window pop ups.

You can use AutoIT script to automate this task. AutoIT is a scripting language for Microsoft windows applications. You will have to download and install AutoIT from this url Download AutoIT

Once downloaded, you can write below code in the script file and invoke that file code just when you need to handle the upload window. Semicolon(;) is used to mark the comments in AutoIT scripts.

;below line states Windows controller to wait for the window with title Open to display. Whatever is the name of window, you need to pass it here.

WinWaitActive("Open")

;below line will enter the file location to be uploaded.
Send("C:\Users\sagar\Documents\onion_fennel_bisque.jpg")

;finally we need to click on Ok or press enter to start the upload process.
Send("{ENTER}")

Here is the complete example.

package seleniumtest;

//autoIT
//TestNG
//Grid

//import the required classes
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public  class AutoIT {
 
 public static void main(String[] args) {
  
     WebDriver driver =null;
     //set the driver path
     System.setProperty("webdriver.chrome.driver",
 "F:\\selenium\\csharp\\chromedriver.exe");
     
     System.setProperty("webdriver.ie.driver", 
"F:\\selenium\\IEDriverServer_Win32_2.43.0\\IEDriverServer.exe");
     
     Date dNow = new Date( );
     
  
     //create new driver instance
    driver = new ChromeDriver();
  
     driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
   
     
      try{
       
       
       driver.get("https://www.pdftoword.com/");
       driver.findElement(By.id("file-uploader")).click();

                        //please note that below line calls the AutoIT
 script which will handle the file upload dialog in google chrome browser. 
Also note that we need to provide the path of exe file which
is created after we compile and build the AutoIT script.
Runtime.getRuntime().exec("F:\\selenium\\handlefile1.exe"); //wait for 2 seconds Thread.sleep(5000); }catch(Exception e){ //print exception if any System.out.println(e.getMessage() ); e.printStackTrace(); } finally{ //close the driver driver.close(); //quit the driver. driver.quit(); } } }

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday, 18 October 2014

How to print all option values from drop down box in Selenium in Java?

Below code shows how we can print the text of all options in drop down box in Selenium in Java.

package seleniumtest;

//import the required classes
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;

public  class ElementIdentification {
 
 public static void main(String[] args) {
  
     WebDriver driver =null;
     //set the driver path
     System.setProperty("webdriver.chrome.driver", "F:\\selenium\\csharp\\chromedriver.exe");
    
     System.setProperty("webdriver.ie.driver", "F:\\selenium\\IEDriverServer_Win32_2.43.0\\IEDriverServer.exe");
    
  
    
     driver = new InternetExplorerDriver();
    
     //set the timeouts for page load and all elements
     driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
     
    
      try{
       
       //open the given web page
   
    driver.get("http://register.rediff.com/commonreg/index.php");
       //driver.get("file:///F:/selenium/selenium-blog.html");
        
    //Maximise the browser window
    driver.manage().window().maximize();
    
    //System.out.println(driver.getPageSource());
    
    System.out.println(driver.getTitle());
    
    
    System.out.println(driver.getCurrentUrl());
    
    WebElement y = driver.findElement(By.id("date_day"));
      
   
    
    Select p = new Select(y);
    p.selectByVisibleText("11");
    String z = p.getFirstSelectedOption().getAttribute("value");
    System.out.println(z);
    
    List <WebElement> k = p.getOptions();

    //Code to print the text values of the options in list box
    for(int i=0; i<k.size();i++)
     System.out.println(k.get(i).getText());
    
      

    
    //wait for 2 seconds
    Thread.sleep(2000);
   }catch(Exception e){
   
   //print exception if any
   System.out.println(e.getMessage() );
   e.printStackTrace();
  }
   finally{
   
   //close the driver
   driver.close();
   //quit the driver.
   driver.quit();
  } 
 }
}


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

How to generate unique random numbers in Selenium in Java?

In software testing projects, we usually need to enter the test data such that data is unique. So you may use below code to create such random unique numbers in Selenium.

//Create a date object
Date d1 = new Date( );

//Create formatting object
SimpleDateFormat formatting = new SimpleDateFormat ("yyyyMMddhhmmss");

//Create unique numbers 
System.out.println("Unique Number is " + formatting.format(d1));

In above code, we have used system date to create unique numbers. By changing the

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday, 11 October 2014

Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones

You may get below error message when working with Selenium Webdriver and Internet Explorer browser.

Unexpected error launching Internet Explorer. Protected Mode settings are not the same for all zones. Enable Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.43 seconds

To fix above error you need to make below setting in Internet Option -> Security Tab as shown in below image.

Enable Protected Mode must be set to the same value (enabled or disabled) for all zones


If you have no permission to modify above settings, you can do it using below code.

DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.
                 INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
WebDriver driver = new InternetExplorerDriver(capabilities);

This will launch Internet explorer such that Enable Protected Mode is set to the same value (enabled or disabled) for all zones.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)

You may get below error while working with selenium.

The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments (String)

To fix this error, you will have to change the compiler compliance level of the project to JRE 1.6 or above in Eclipse.
To open below window, you will have to right click on the Java Project folder you are working on.


I was getting the sendKeys error when I was using JRE 1.4 compliance level. After changing the compiler compliance level to 1.6, the error was resolved.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Saturday, 30 August 2014

timeout: Timed out receiving message from renderer in Selenium and chrome

You may get exception saying - timeout: Timed out receiving message from renderer when working with Selenium web driver and chrome browser.

I fixed this exception using below statement in Java.

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

I was getting the exception earlier when the page load time out was 20 seconds. I increased the page load time out to 60 seconds and it started working like a charm.

As a good practise, always make sure that page load time out is at least 60 seconds.

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

Tuesday, 1 July 2014

Selenium online training in Auckland, Wellington, Hamilton, Tauranga, Christchurch

If you want to learn Selenium quickly, you can attend the online classes/tutions. Please find more details about online training of Selenium in  Auckland, Wellington, Hamilton, Tauranga, Christchurch.

Selenium Online Training features
  1. We will have interactive sessions via online meetings with video conferencing.
  2. To register for the online course, you have to send an email to reply2sagar@gmail.com
  3. Further details will be sent to you after your registration is confirmed.
  4. You can ask questions during the session and clarify your doubts.
  5. You should have a headset and computer with Internet Connection.
  6. Live training will be given on Selenium.
  7. The cost of selenium course is $250.
Selenium Course Syllabus
  1. Selenium Basics.
  2. Selenium Webdriver - Element Identification methods.
  3. Handling multiple frames, windows.
  4. Automation Frameworks in Selenium Webdriver.
  5. Java Basics - switch and loops
  6. Strings, Arrays, Date Time, Maths
  7. Classes and members - access modifiers and constructors.
  8. abstract classes and interfaces
  9. Encapsulations, inheritance
  10. Polymorphism - overloading and overriding
  11. Streams.
  12. Exceptions.
  13. Java and Excel
  14. Selenium - Installation in Java
  15. Selenium and different browsers.
  16. Exceptions in Selenium.
  17. Identifying Elements using xpath, css, id, classname, tags.
  18. Entering Data in edit boxes.
  19. working with links , buttons, checkboxes, weblists, radio buttons.
  20. Adding Synchronization Points in Selenium.
Timings and Duration for online Selenium Training
  1. New batch starts every Saturday at 4 PM and 9 PM India time.
  2. Online Classes will be conducted on every Saturday and Sunday.
  3. Each class will be of 1 hour.
  4. Timing is 4 PM and 9 PM India time.
Many IT Professionals in New Zealand have found this online course very useful to learn the important concepts of Selenium Webdriver. So if you wanna add extra skill to your resume, you can join this class. You have to just send an email to reply2sagar@gmail.com

Please give your inputs, suggestions, feedback to Us about above Selenium topic. We value your thoughts. You can write to me at reply2sagar@gmail.com

Selenium Online Training in India, USA, UK, Europe, Australia, New Zealand

Hello friends,
                    If you want to learn Selenium quickly, you can attend the online classes/tutions. Please find more details about online training of Selenium.

Selenium Online Training features
  1. We will have interactive sessions via online meetings with video conferencing.
  2. To register for the online course, you have to send an email to reply2sagar@gmail.com
  3. Further details will be sent to you after your registration is confirmed.
  4. You can ask questions during the session and clarify your doubts.
  5. You should have a headset and computer with Internet Connection.
  6. Live training will be given on Selenium.
Selenium Course Syllabus
  1. Selenium Basics.
  2. Selenium Webdriver - Element Identification methods.
  3. Handling multiple frames, windows.
  4. Automation Frameworks in Selenium Webdriver.
  5. Java Basics - switch and loops
  6. Strings, Arrays, Date Time, Maths
  7. Classes and members - access modifiers and constructors.
  8. abstract classes and interfaces
  9. Encapsulations, inheritance
  10. Polymorphism - overloading and overriding
  11. Streams.
  12. Exceptions.
  13. Java and Excel
  14. Selenium - Installation in Java
  15. Selenium and different browsers.
  16. Exceptions in Selenium.
  17. Identifying Elements using xpath, css, id, classname, tags.
  18. Entering Data in edit boxes.
  19. working with links , buttons, checkboxes, weblists, radio buttons.
  20. Adding Synchronization Points in Selenium.
Timings and Duration for online Selenium Training
  1. New batch starts every Saturday at 4 PM and 9 PM India time.
  2. Online Classes will be conducted on every Saturday and Sunday.
  3. Each class will be of 1 hour.
In below table, you will find the timings at which I conduct the classes for selenium.

NoRegionsLocal TimingIndia Timing
1Australia(Sydney)3 PM Local Time10:30 AM Local Time
2Asia(Mumbai)12 PM Local Time12 PM Local Time
3Europe(London)9 AM Local Time1:30 PM Local Time
4Africa(Cape Town)12:30 PM Local Time4 PM Local Time
5Americas(NY)11:30 AM Local Time9 PM Local Time


You can get in touch with me by gmail, facebook, what's app or skype.

Gmailreply2sagar@gmail.com
Skyperevert2sagar
Facebookhttps://www.facebook.com/sagar.salunke.186
What's app+919850182384

You can have a look at below Study material on selenium webdriver.



  • Watch Selenium Videos
  • Buy books on Selenium Webdriver

  • Many Professionals have found this online course very useful to learn the important concepts of Selenium Webdriver. So if you wanna add extra skill to your resume, you can join this class. You have to just send an email to reply2sagar@gmail.com

    Countries which we cover for Selenium training are given below
    We provide the Selenium course training in all countries across the world as mentioned below.

    1. Australia and New Zealand
    2. Asian Countries
    3. European Countries
    4. African Countries
    5. American Countries

    Australia and New Zealand
    1. Australia - Sydney, Melbourne, Perth, Brisbane, Adelaide, Gold Coast, New Castle, Canberra, Sunshine Coast,Wollongong, Hobart, Geelong, Townsville, Cairns, Darwin, Toowoomba, Ballarat, Bendigo, Launceston, Albury-Wodonga, Mackay, Rockhampton, Bundaberg, Bunbury, Coffs Harbour, Wagga Wagga, Hervey Bay, Mildura-Wentworth, Shepparton-Mooroopna, Gladstone-Tannum Sands,  Port Macquarie, Tamworth, Traralgon-Morwell, Orange, Geraldton, Bowral-Mittagong, Dubbo, Nowra-Bomaderry, Bathurst, Warrnambool, Kalgoorlie-Boulder, Busselton, Albany, Warragul-Drouin, Devonport
    2. New Zealand - Auckland, Wellington, Hamilton, Tauranga, Christchurch, Napier-Hastings, Dunedin, Palmerston North, Nelson, Rotorua, New Plymouth, Whangarei
    Asian Countries
    1. India - Pune, Bangalore, Chennai, Delhi, Mumbai, Hyderabad, Kolkata
    2. Singapore - South West, Central, North West
    3. China - Beijing, Hebei, Tiajin, Shanxi, Mongolia, Liaoning, Jilin, Heilongjiang, Shanghai, Jiangsu, Zhejiang, Anhui, Fujian, Jiangxi, Shandong, Henan, Hubei, Hunan, Gaungdong, Hainan, Sichuan, Chongqing, Guizhou, Yunnan, Gansu, Qinghai, Hong-kong
    4. Indonesia - Jakarta, Surabaya, Bandung, Bekasi, Medan, Tangerang, Depok, Semarang, Palembang, Makassar, Bogor, Batam, Pekanbaru, Padang, Malang, Denpasar, Sumarinda, Tasikmalaya
    5. Bangladesh - Dhaka, Chittagong, Khulna, Narayanganj, Sylhet, Tongi, Rajshahi, Bogra, Barisal, Comilla
    6. Japan - Tokyo, Yokohama, Osaka, Nagoya, Sapporo, Kobe, Kyoto, Fukuoka, Kawasaki, Saitama
    7. Phillipines - Quezon, Manila, Caloocan, Davao, Cebu, Zamboanga, Antipolo, Pasig, Taguig, Cagayan-de-Oro
    8. Thailand - Bangkok, Nonthaburi, Pak-Kret, Hat-Yai, Udon-Thani, Chiang-Mai
    9. Turkey - Istanbul, Ankara, Izmir, Bursa, Adana, Gaziantep
    10. Burma - Yangon, Mandalay, Naypyidaw, Mawlamyaing, Taunggyi, Pathein, Bago, Pyay, Monywa, Sittwe
    11. South Korea - Seoul, Busan, Incheon, Daegu, Daejeon, Gwangju, Ulsan, Suwon, Changwon, Goyang, Seongnam, Yongin, Bucheon, Ansan, Cheongju, Jeonju, Namyangju, Anyang, Cheonan, Hwaseong
    12. North Korea -  Pyongyang, Hamhung, Chongjin, Nampo, Sunchon, Sinuiju 
    13. Russia - Moscow, Saint-Petersburg, Novosibirsk, Yekaterinburg, Nizhny-Novgorod, Samara, Kazan, Omsk, Chelyabinsk, Rostov-na-Donu
    14. Malaysia - Kuala-Lumpur, Johor-Bahru, Ipoh, Shah-Alam, Petaling-Jaya, Kuching, Kota-Kinabalu, Kuala-Terengganu, Malacca, Alor-Setar, Miri, George-Town
    15. Saudi Arebia - Riyadh, Jeddah, Mecca, Medina, Al-Ahsa, Taif, Dammam, Khamis-Mushait, Buraidah, Khobar
    16. Taiwan- New-Taipei, Kaohsiung, Taichung, Taipei, Tainan, Hsinchu, Taoyuan, Keelung, Zhongli, Chiayi
    17. Sri Lanka - Colombo, Dehiwala-Mount-Lavinia, Moratuwa, Sri-Jayawardenapura-Kotte, Negombo, Kandy
    18. UAE - Dubai, Abu-Dhabi, Sharjah, Al-Ain, Ajman
    19. Israel - Jerusalem, Tel Aviv, Haifa, Rishon-LeZion, Ashdod, Petah-Tikva, Beersheba, Netanya, Holon, Bnei Brak
    20. Qatar - Doha-capital, AL-wakair, Abu-az-Zuluf, Abu-Thaylah
    European Countries
    1. UK - London, Bath, Birmingham, Bradford, Bristol, Sheffield, Nottingham, Liverpool, Tyneside, Hampshire, Glasgow, Yorkshire, Midlands, Manchester, Bristol, Belfast, Edinburgh, Brighton, Dorset, Leicester, Portsmouth, Reading, Teesside, Potteries.
    2. Germany- Berlin, Hamburg, Munich, Cologne, Frankfurt, Stuttgart, Dusseldorf, Dortmund, Essen, Bremen, Dresden, Leipzig, Hannover, Nuremberg, Duisburg, Bochum, Wuppertal, Bonn, Bielefeld, Mannheim, Karlsruhe, Munster, Warragul-Drouin, Wiesbaden, Augsburg, Aachen, Mönchengladbach, Gelsenkirchen, Braunschweig, Chemnitz, Kiel, Krefeld, Halle, Freiburg, Magdeburg, Oberhausen, Lübeck, Erfurt, Rostock, Mainz, Kassel, Hagen, Hamm, Mülheim-an-der-Ruhr, Saarbrücken, Herne, Ludwigshafen- am-Rhein, Osnabrück, Oldenburg, Leverkusen, Solingen, Potsdam, Neuss, Heidelberg, Paderborn, Darmstadt, Regensburg, Würzburg, Ingolstadt,  Heilbronn, Ulm, Göttingen, Wolfsburg, Offenbach-am-Main, Pforzheim, Recklinghausen, Bottrop,  Fürth,Bremerhaven,Reutlingen,Remscheid,Koblenz,Bergisch-Gladbach,Trier, Erlangen, Moers, Jena, Salzgitter, Siegen, Cottbus, Hildesheim.
    3. France- Paris, Marseille, Lyon, Toulouse, Nice, Nantes, Strasbourg, Montpellier, Bordeaux, Lille, Rennes, LeHavre, Reims, Saint-Étienne, Toulon, Grenoble, Angers, Dijon, Brest, Le-Mans, Clermont-Ferrand, Amiens, Aix-en-Provence, Limoges, Nîmes, Tours, Saint-Denis, Villeurbanne, Metz, Besançon, Caen, Orléans, Mulhouse, Rouen, Boulogne-Billancourt, Perpignan, Nancy, Roubaix, Fort-de-France, Argenteuil, Tourcoing, Montreuil, Saint-Paul, Avignon, Saint-Denis, Versailles, Nanterre, Poitiers, Créteil, Aulnay-sous-Bois, Vitry-sur-Seine, Pau, Calais, Colombes, La-Rochelle, Asnières-sur-Seine.
    4. Spain - Madrid, Barcelona, Valencia, Seville, Bilbao, Málaga, Oviedo–Gijón–Avilés, Alicante–Elche, Las-Palmas, Zaragoza, Murcia–Orihuela, Palma, Vigo, Cartagena, Cádiz, San-Sebastián, Valladolid, Tarragona, Córdoba, Pamplona, Alzira–Xàtiva, Vitoria-Gasteiz, Huelva, Almería, Salamanca, León, Albacete, Jaén–Martos, Burgos, Logroño, Ferrol–Narón, Lleida, Girona–Salt, Badajoz, Ourense, Benidorm, Gandia, Blanes, Manresa, Marbella, Torrelavega, Vic–Manlleu, Guadalajara, Lugo, Palencia,Toledo.
    5. Sweden - Stockholm, Gothenburg, Malmö,Uppsala, Linköping, Västerås, Örebro, Norrköping, Helsingborg, Jönköping, Lund, Umeå, Gävle, Borås, Eskilstuna, Södertälje, Karlstad, Täby, Växjö, Halmstad.
    6. Belgium - Antwerp, Ghent, Charleroi, Liège, Brussels, Bruges, Schaerbeek, Anderlecht, Namur, Leuven, Mons, Mechelen, Ixelles, Aalst, Uccle, La-Louvière, Hasselt, Kortrijk, Sint-Niklaas, Ostend, Tournai, Genk, Seraing, Roeselare, Mouscron, Verviers, Forest, Saint-Gilles, Jette, Beveren, Etterbeek, Dendermonde, Beringen, Turnhout, Vilvoorde, Dilbeek, Lokeren, Sint-Truiden, Herstal, Geel, Ninove, Maasmechelen, Brasschaat, Halle, Waregem, Châtelet, Grimbergen, MolYpres, Lier, Evergem, Schoten, Knokke-Heist, Lommel, Wavre, Tienen, Binche, Geraardsbergen, Menen, Bilzen, Wevelgem.
    7. Switzerland - Zürich, Geneva, Basel, Lausanne, Bern, Lucerne, Winterthur, St-Gallen, Lugano, Biel, Thun, Köniz, La-Chaux-de-Fonds, Schaffhausen, Fribourg, Vernier, Chur, Neuchâtel, Uster, Sion, Kriens.
    8. Denmark - Copenhagena, Aarhus, Odense, Aalborgb, Frederiksberga, Esbjerg, Gentoftea, Gladsaxea, Randers, Kolding, Horsens, Lyngby-Taarbæka, Vejle, Hvidovrea, Roskilde, Helsingør, Herning, Silkeborg, Naestved, Greve-Stranda, Tarnbya, Fredericia, Ballerupa, Rodovrea, Viborg, Koge, Holstebro, Brondbya, Taastrupa, Slagelse, Hillerod, Albertslunda, Sonderborg, Svendborg, Herleva, Holbaek, Hjorring, Horsholm, Frederikshavn, Glostrupa, Haderslev, Norresundbyb, Ringsted, Skive.
    9. Greece - Athens, Thessaloniki, Patras, Piraeus, Larissa, Heraklion, Peristeri, Kallithea, Acharnes, Kalamaria, Nikaia, Glyfada, Volos, Ilio, Ilioupoli, Keratsini, Evosmos, Chalandri, Nea-Smyrni, Marousi, Agios-Dimitrios, Zografou, Egaleo, Nea-Ionia, Ioannina, Palaio-Faliro, Korydallos, Trikala, Vyronas, Agia-Paraskevi , Galatsi, Chalcis, Petroupoli, Serres, Alexandroupoli, Xanthi, Katerini, Kalamata, Kavala, Chania, Lamia , Komotini, Irakleio, Rhodes, Kifissia, Agrinio, Stavroupoli, Chaidari, Drama, Veria , Alimos, Kozani, Polichni, Karditsa, Sykies, Ampelokpoi, Pylaia, Agioi-Anargyroi, Argyroupoli, Ano Liosia,Nea Ionia, Rethymno, Ptolemaida, Tripoli, Cholargos, Vrilissia, Corinth, Metamorfosi , Giannitsa, Voula, Kamatero, Mytilene, Neapoli, Chios, Agia Varvara , Kaisariani, Nea-Filadelfeia, Moschato, Perama, Salamis, Eleusina, Corfu, Pyrgos.
    10. Georgia - Tbilisi, Kutaisi, Batumi, Rustavi, Zugdidi, Gori, Poti, Samtredia, Khashuri, Senaki, Zestafoni,Marneuli, Telavi, Akhaltsikhe, Kobuleti, Ozurgeti, Tsqaltubo, Kaspi, Gardabani, Chiatura, Tqibuli, Borjomi, Sagarejo, Bolnisi, Khoni, Gurjaani, Akhalkalaki .
    11. Italy - Rome, Milan, Naples, Turin, Palermo, Genoa, Bologna, Florence, Bari, Catania, Venice, Verona, Messina, Padua, Trieste, Taranto, Brescia, Prato, Reggio-Calabria, Modena, Parma, Perugia, Reggio, Livorno, Ravenna, Cagliari, Foggia, Rimini, Salerno, Ferrara, Sassari, Syracuse, Pescara, Monza, Latina, Bergamo, Forlì, Trento, Vicenza, Terni, Novara, Bolzano, Piacenza, Ancona, Arezzo, Andria, Udine, Cesena, Lecce, La-Spezia, Pesaro, Alessandria, Barletta, Catanzaro, Pistoia, Brindisi, Pisa, Torre-del-Greco, Como, Lucca, Guidonia-Montecelio, Pozzuoli, Treviso, Marsala, Grosseto, Busto ,Arsizio, Varese, Sesto-San-Giovanni, Casoria, Caserta, Gela, Asti, Cinisello-Balsamo, Ragusa,  L’Aquila, Cremona, Lamezia-Terme, Pavia, Fiumicino, Massa, Trapani, Aprilia, Cosenza, Altamura, Imola, Carpi, Potenza, Carrara, Castellammare-di-Stabia, Viareggio, Fano, Afragola, Vigevano, Viterbo, Vittoria, Savona, Benevento, Crotone, Pomezia, Matera, Caltanissetta, Molfetta,  Marano-di-Napoli, Agrigento, Legnano, Cerignola, Moncalieri, Foligno, Faenza, Manfredonia, Sanremo,  Tivoli, Bitonto, Avellino, Bagheria, Acerra, Olbia, Cuneo, Anzio, San-Severo, Modica, Teramo,  Bisceglie, Ercolano, Siena, Chieti, Portici, Trani, Velletri, Acireale, Rovigo, Civitavecchia, Gallarate, Pordenone, Aversa, Montesilvano, Mazara-del-Vallo, Ascoli-Piceno, Battipaglia, Campobasso, Scafati, Casalnuovo-di-Napoli, Rho, Chioggia, Scandicci,  Collegno.
    12. IcelandReykjavík, Kópavogur, Hafnarfjörður, Akureyri, Keflavík, Garðabær, Mosfellsbær, Akranes, Selfoss, Njarðvík, Seltjarnarnes, Vestmannaeyjar, Grindavík, Sauðárkrókur, Ísafjörður, Álftanes, Hveragerði, Egilsstaðir, Húsavík, Borgarnes, Sandgerði, Höfn, Þorlákshöfn, Dalvík, Garður, Neskaupstaður, Siglufjörður, Reyðarfjörður, Vogar, Stykkishólmur, Eskifjörður, Ólafsvík.
    13. IrelandDublin, Ennis, Cork, Kilkenny, Limerick, Tralee, Galway, Carlow, Waterford, Newbridge, Drogheda, Naas, Dundalk, Athlone, Swords, Portlaoise, Bray, Mullingar, Navan, Wexford.
    14. UkraineKyiv, Kharkiv, Dnipropetrovsk, Odesa, Donetsk, Zaporizhia, Lviv, Kryvyi Rih, Mykolaiv, Mariupol, Luhansk, Makiivka, Vinnytsia, Simferopol, Sevastopol, Kherson, Poltava, Chernihiv, Cherkasy
    15. PolandWarszawa, Krakow, Lodz, Wroclaw, Poznan, Gdansk, Szczecin, Bydgoszcz, Lublin, Katowice, Bialystok, Gdynia, Czestochowa, Radom, Sosnowiec, Torun, Kielce, Gliwice, Zabrze, Bytom, Olsztyn, Bielsko-Biala, Rzeszow, Ruda-Slaska, Rybnik, Tychy, Dabrowa-Gornicza
    16. NetherlandsAmsterdam, Enschede, Rotterdam, Apeldoorn, The Hague, Haarlem, Utrecht, Amersfoort, Eindhoven, Zaanstad, Tilburg, Arnhem, Groningen, Haarlemmermeer, Almere, S-Hertogenbosch, Breda, Zoetermeer, Nijmegen, Zwolle.
    17. RomaniaBucharest, Cluj-Napoca, Timisoara, Iasi, Constanța, Craiova, Brasov, Galați, Ploiesti, Oradea, Braila, Arad, Pitești, Sibiu, Bacau, Targu-Mureș, Baia-Mare, Buzau, Botoșani, Satu-Mare, Ramnicu-Valcea, Drobeta-Turnu-Severin, Suceava, Piatra-Neamț, Targu-Jiu, Targoviste, Focsani, Bistrita, Tulcea, Resita, Slatina, Calarasi, Alba-Iulia, Giurgiu, Deva, Hunedoara, Zalau, Sfantu-Gheorghe, Barlad, Vaslui, Roman, Turda, Medias, Slobozia, Alexandria, Voluntari, Lugoj, Medgidia, Onesti, Miercurea-Ciuc, Sighetu-Marmației.
    18. KazakhstanAktau, Aktobe, Almaty, Arkalyk,Astana, Atyrau, Baikonur, Balqash, Zhezkazgan, Karagandy, Kentau,  Kyzylorda, Kokshetau, Kostanay, Zhanaozen, Pavlodar, Petropavl, Ridder, Saran, Satpayev, Semey, Stepnogorsk, Taldykorgan, Taraz, Temirtau, Turkistan, Oral, Oskemen, Shymkent, Shahtinsk, Shuchinsk, Ekibastuz.
    19. Hungary  - Budapest, Debrecen, Miskolc, Szeged, Pecs, Gyor, Nyíregyhaza, Kecskemet, Szekesfehervar, Szombathely, Szolnok, Tatabanya, Kaposvar, Erd, Veszprem, Zalaegerszeg, Sopron, Eger, Nagykanizsa. 
    20. Portugal  - Lisbon, Agualva-Cacem, Sintra, Queluz, Vila-Nova-de-Gaia, Guimaraes, Porto, Viseu, Braga, Rio-Tinto, Amadora, Aveiro, Funchal, Odivelas, Coimbra, Matosinhos, Setubal, Amora, Almada, Ponta-Delgada.
    21. Bulgaria - Sofia, Plovdiv, Varna, Burgas, Ruse, Stara-Zagora, Pleven, Sliven, Dobrich, Pernik, Shumen, Haskovo, Yambol, Pazardzhik, Blagoevgrad, Veliko-Tarnovo, Vratsa, Gabrovo, Asenovgrad, Vidin.
    22. Azerbaijan  - Baku, Khachmaz, Sumqayit, Agdam, Ganja, Jalilabad, Mingachevir, Khankandi, Lankaran, Shirvan, Nakhchivan, Shamkir, Shaki, Yevlakh.
    23. Belarus - Minsk, Barysaw, Salihorsk, Maladzyechna, Vitsyebsk, Orsha, Navapolatsk, Polatsk, Mahilyow, Babruysk, Homyel, Mazyr, Zhlobin, Brest, Baranavichy, Pinsk, Hrodna, Lida.
    24. Slovakia - Bratislava, Prievidza, Kosice, Zvolen, Presov, Povazska-Bystrica, Zilina, Banska-Bystrica, Nitra, Trnava, Martin, Trencín, Poprad.
    25. Croatia - Zagreb, Split, Rijeka, Osijek, Zadar, Pula, Slavonski-Brod, Karlovac, Varazdin, Sibenik, Sisak, Vinkovci, Velika-Gorica.
    26. Moldova - Chisinau, Tiraspol, Balti, Bender, Ribnita, Cahul, Ungheni.
    27. Serbia  - Belgrade, Novi-Sad, Nis, Kragujevac, Subotica, Zrenjanin, Pancevo, Cacak, Novi -Pazar, Kraljevo, Smederevo, Leskovac, Valjevo, Krusevac, Vranje, Sabac, Uzice, Sombor, Pozarevac, Pirot.
    28. Macedonia - Skopje, Bitola, Kumanovo, Prilep, Tetovo, Veles, Stip, Ohrid, Gostivar, Strumica.
    29. Finland - Helsinki, Espoo, Tampere, Vantaa, Oulu, Turku, Kuopio, Lahti, Kouvola, Pori, Joensuu, Lappeenranta, Hameenlinna, Vaasa, Rovaniemi, Seinajoki, Salo, Kotka.
    30. Armenia - Yerevan, Charentsavan, Gyumri, Vanadzor, Vagharshapat, Hrazdan, Abovyan, Kapan, Armavir, Gavar, Artashat.
    31. Norway - Oslo, Bergen, Stavanger, Trondheim, Kristiansand, Sarpsborg, Drammen, Skien, Tromso.
    32. Montenegro - Podgorica, Niksic, Pljevlja, Bijelo-Polje.
    33. Latvia - Riga, Vilnius, Tallinn, Kaunas, Klaipeda, Siauliai, Tartu, Panevezys, Daugavpils.
    34. Albania - Tirana, Durres, Vlore, Elbasan, Shkoder, Fier, Korce, Gjirokaster.
    35. Slovenia -  Ljubljana, Celje, Kranj, Velenje, Koper.
    36. Estonia - Tallinn, Tartu, Narva, Parnu, Kohtla-Jarve.
    37. Lithuania - Vilnius, Kaunas, Klaipeda, Siauliai, Panevezys.
    38. Cyprus - Nicosia, Limassol, Larnaca, Paphos, Kyrenia, Famagusta.
    39. Kosovo - Pristina, Prizren, Ferizaj, Pec, Gjakova, Gnjilane, Podujevo, Mitrovica, Vucitrn, Suva-Reka, Glogovac, Lipljan, Orahovac, Malisevo, Skenderaj, Vitina, Decan.
    40. Luxembourg - Luxembourg-City, Esch-sur-Alzette, Dudelange.
    41. Northern-Cyprus - North-Nicosia, Famagusta, Kyrenia.

    African Countries
    1. South Africa - Cape Town, Johannesburg.
    2. Nigeria

    North and South American Countries
    1. USA - New York, New Jersey,Boston, Chicago, Houston, Philadelphia, Phoenix, San Antonio, San Diego, Dallas, San Jose, Austin, Indianapolis, San Francisco, Detroit, El Paso, Memphis, Seattle, Denver, Washington, Nashville, Baltimore,Louisville, Portland, Las Vegas, Milwaukee, Albuquerque, Tucson, Fresno, Sacramento, Long Beach, Kansas City, Mesa, Virginia Beach, Atlanta, Colorado Springs, Omaha, Raleigh, Miami, Oakland, Minneapolis, Tulsa, Cleveland, Wichita, Arlington, New Orleans, Bakersfield, Tampa, Honolulu, Aurora, Anaheim, Santa Ana, St. Louis, Riverside, Corpus Christi, Lexington, Pittsburgh, Anchorage, Stockton, Cincinnati, Saint Paul, Toledo, Greensboro Newark, Plano, Henderson, Lincoln, Buffalo, Jersey City, Chula Vista, Fort Wayne, Orlando, St. Petersburg, Chandler, Laredo, Norfolk, Durham, Madison, Lubbock, Irvine, Winston–Salem, Glendale, Garland, Hialeah, Reno, Chesapeake, Gilbert, Baton Rouge, Irving, Scottsdale, North Las Vegas, Fremont, Boise, Richmond, San Bernardino, Birmingham, Spokane Rochester, Des Moines, Modesto, Fayetteville, Tacoma, Oxnard, Fontana, Columbus, Montgomery, Moreno Valley, Shreveport, Aurora, Yonkers, Akron, Huntington Beach, Little Rock, Augusta, Amarillo, Glendale, Mobile, Grand Rapids, Salt Lake City, Tallahassee, Huntsville, Grand Prairie, Knoxville, Worcester, Newport News, Brownsville, Overland Park, Santa Clarita, Providence, Garden Grove, Chattanooga, Oceanside, Jackson, Fort Lauderdale, Santa Rosa, Rancho Cucamonga, Port St. Lucie, Tempe, Ontario, Vancouver, Cape Coral, Sioux Falls, Springfield, Peoria, Pembroke Pines, Elk Grove, Salem, Lancaster, Corona, Eugene, Palmdale, Salinas, Springfield, Pasadena, Fort Collins, Hayward, Pomona, Cary, Rockford, Alexandria Escondido, McKinney, Kansas City, Joliet, Sunnyvale, Torrance, Bridgeport, Lakewood, Hollywood, Paterson, Naperville, Syracuse Mesquite, Dayton, Savannah, Clarksville, Orange, Pasadena, Fullerton, Killeen, Frisco, Hampton, McAllen, Warren Bellevue, West Valley City, Columbia, Olathe, Sterling Heights, New Haven, Miramar, Waco, Thousand Oaks, Cedar Rapids, Charleston, Visalia, Topeka, Elizabeth, Gainesville, Thornton,Roseville, Carrollton, Coral Springs, Stamford,Simi Valley,Concord,Hartford, Kent, Lafayette,Midland,Surprise,Denton,Victorville,Evansville, Santa Clara,Abilene,Athens,Vallejo,Allentown,Norman,Beaumont, Independence,Murfreesboro,Ann Arbor,Springfield,Berkeley, Peoria,Provo,El Monte,Columbia,Lansing,Fargo,Downey,Costa Mesa Wilmington, Arvada,Inglewood, Miami Gardens, Carlsbad, Westminster, Rochester, Odessa,Manchester,Elgin, West Jordan,Round Rock, Clearwater, Waterbury, Gresham,Fairfield,Billings,Lowell,Ventura,Pueblo,High Point, West Covina,Richmond,Murrieta,Cambridge,Antioch,Temecula,Norwalk,Centennial, Everett,Palm Bay,Wichita Falls,Green Bay,Daly City,Burbank,Richardson, Pompano Beach,North Charleston,Broken Arrow,Boulder,West Palm Beach, Santa Maria,El Cajon,Davenport,Rialto,Las Cruces,San Mateo,Lewisville, South Bend,Lakeland,Erie,Tyler,Pearland,College Station
    2. Canada - Toronto, Montreal, Vancouver, Edmonton, Winnipeg, Calgary, Ottawa–Gatineau, Quebec



    Please give your inputs, suggestions, feedback to Us about above Selenium topic. We value your thoughts. You can write to me at reply2sagar@gmail.com

    Thursday, 19 June 2014

    Selenium code to set google preferences and search the keywords

    Below code will change the google search settings and also search some keywords.

    package seleniumtest;
    
    import java.io.File;
    import java.io.FileWriter;
    import java.io.PrintStream;
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    
    import org.openqa.selenium.By;
    import org.openqa.selenium.Keys;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.ie.*;
    import org.openqa.selenium.interactions.Action;
    import org.openqa.selenium.interactions.Actions;
    
    public  class Google {
     
     
     public static void main(String[] args) {
     
         WebDriver driver =null;
         System.setProperty("webdriver.chrome.driver", "F:\\selenium\\csharp\\chromedriver.exe");
       driver = new ChromeDriver();
       driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
       driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
       driver.manage().window().maximize();
       
     try{
      
      driver.get("https://www.google.co.in/preferences?hl=en-IN&fg=1"); 
    driver.findElement(By.xpath("//div[text()='Never show Instant results.']")).click();
    driver.findElement(By.xpath("//div[text()='Save']")).click();
    
    driver.get("https://www.google.co.in");  
    
    //String x = driver.switchTo().frame(0).switchTo().frame(0).findElement(By.tagName("h3")).getText();
    //String x = driver.switchTo().frame(1).findElement(By.tagName("h3")).getText();
    //String x = driver.switchTo().frame("view").switchTo().frame(0).getPageSource();
    //System.out.println(x);
    
    String str = "Selenium How to ";
    String d = "";
     
    for (int i=1 ;i<=26;i++)
     
    {
     char x = (char) (64+i);
     
    driver.findElement(By.cssSelector("input[name=q]")).sendKeys(str + x);
    
    Thread.sleep(2000);
    List <WebElement> tr =  driver.findElements(By.xpath("//table[@class='gssb_m']//tr"));
    
    for (int co=0 ; co<tr.size();co=co+2)
    {
     
     d= d + tr.get(co).getText() + "\r\n";
    }
    
    driver.findElement(By.id("lst-ib")).clear();
    
    }
    
    System.out.println(d);
    String filePath = "f:\\videos\\"+ str +".txt";
         
       if ((new File(filePath)).exists() )
        (new File(filePath)).delete();
         
         
     File temp = new File(filePath);
     FileWriter fw = new FileWriter(temp,true);
     fw.append(d);
     fw.close();
         
    
    
     
    
        Thread.sleep(4000);
        //driver.navigate();
    //driver.navigate("http://www.google.com");
      
    }catch(Exception e){
    
     //System.out.println(e.getLocalizedMessage());
       
       e.printStackTrace(new PrintStream(System.out));
       
      }
       
       
      finally{
       driver.close();
       driver.quit();
      } 
       
      
      
      
      
     }
     
     
    
     
    }


    What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

    Friday, 28 March 2014

    How to read data from excel sheet using Apache POI in Java?

    Here is the complete Java code to read and write from the excel sheet in Java. Please note that you will have to download and add POI library to current project from url http://poi.apache.org/download.html

    The package org.apache.poi.hssf contains the xls implementations
    The package org.apache.poi.xssf contains the xlsx implementations

    package framework;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.util.Iterator;
    
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Row;
    
    public class Excel {
    
     /**
      * @param args
      */
     public static void main(String[] args) {
        
    FileInputStream file = null;
    HSSFWorkbook workbook;
    
    Futil.createHtmlHead(1);
    
    
    try {
     
     
     
       
     file = new FileInputStream(new File("F:\\selenium\\batch.xls"));
     workbook = new HSSFWorkbook(file);
     HSSFSheet sheet = workbook.getSheetAt(0);
     Iterator<Row> rowIterator = sheet.iterator();
     int k=0;
     while (rowIterator.hasNext())  
        {
        rowIterator.next();
        k++;
        }
     
     System.out.println("Total rows in the sheet " + k);
     int intRowCounter = 1;
     Row row =  sheet.getRow(intRowCounter);
     System.out.println("Data in the excel " +  readcell(row,2));
     
     row.getCell(1).setCellValue("salunke");
     FileOutputStream fos = new FileOutputStream("F:\\selenium\\batch.xls");
        workbook.write(fos);
        fos.close();
    
    } 
    catch(Exception ex){
    System.out.println("Exception occured" + ex.toString());
    }
    
    finally{
     
     try{
     file.close();
     }catch(Exception ex){
      
      System.out.println(ex.toString());
     }
     
     
    }
    
     }//main method ends
     
     
     
    //to read the data
     
     public static String readcell(Row rowObj,int colNum)
     {
      String x="";
     try{
      if  (rowObj.getCell(colNum).getCellType() == 1)
       x = rowObj.getCell(colNum).getStringCellValue();
      else if  (rowObj.getCell(colNum).getCellType() == 0)
       x = "" + (int)rowObj.getCell(colNum).getNumericCellValue();
     }
     catch(Exception e){
      x = "";
     //System.out.println(e.toString() + " while reading a cell");
      }
      
      return x;
     }
     
     
     //to write the data
     public static void writeCell(Row rowObj,int colNum, String data)
     {
      
      try{
        
        rowObj.getCell(colNum).setCellValue((String) data);
       
      }
      catch(Exception e){
      
       System.out.println(e.toString() + " while writing a cell");
      }
      
      
     }
     
     
    
    } //class ends
    
    
    
    
    You may also like to read below topics.
    1. Press key in Selenium Webdriver in Java
    2. Read Table Data in Selenium Webdriver in Java
    3. Take the screenshot in Selenium Webdriver in Java
    4. Execute JavaScript in Selenium Webdriver in Java
    5. Handle multiple browser windows in Selenium Webdriver in Java
    6. Double-Click on the Element in Selenium Webdriver in Java
    7. Exceptions in Selenium Webdriver in Java
    8. Synchronization in Selenium Webdriver in Java
    9. Frameworks in Selenium
    What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

    Buy Best Selenium Books

    Contributors