Skip to main content

Selenium Rare Tips - Part I

Hi all,
Here I am going to list out some rare and useful tips for selenium users.


1. Start/Shutdown SeleniumServer in proper way
  1. public static void startSeleniumServer() throws Exception {    
  2.     try {
  3.         ServerSocket serverSocket = new ServerSocket(RemoteControlConfiguration.DEFAULT_PORT);
  4.         serverSocket.close();
  5.        
  6.                 //Server not up, start it
  7.                 try {
  8.                          RemoteControlConfiguration rcc = new RemoteControlConfiguration();
  9.                          rcc.setPort(RemoteControlConfiguration.DEFAULT_PORT);
  10.                          server = new SeleniumServer(false, rcc);    
  11.                 } catch (Exception e) {
  12.                         System.err.println("Could not create Selenium Server because of: " + e.getMessage());
  13.                         e.printStackTrace();
  14.                 }
  15.                
  16.                 try {
  17.                         server.start();
  18.                         System.out.println("Server started");
  19.                 } catch (Exception e) {
  20.                         System.err.println("Could not start Selenium Server because of: " + e.getMessage());
  21.                         e.printStackTrace();
  22.                 }
  23.                
  24.         } catch (BindException e) {
  25.                 System.out.println("Selenium server already up, will reuse...");
  26.         }
  27. }

  1. public void tearDown() throws Exception {
  2.     selenium.stop();
  3.     if(seleniumServer != null) {
  4.         try {
  5.             selenium.shutDownSeleniumServer();
  6.             seleniumServer .stop();
  7.             seleniumServer = null;
  8.         }  catch(Exception e) {
  9.             e.printStackTrace();
  10.         }
  11.     }
  12. }

OR you want to shoudown via Browser, use below command
http://localhost:4444/selenium-server/driver/?cmd=shutDownSeleniumServer


2. To Scroll by postion
selenium.getEval("window.scrollBy(0,200)");
--- Here 0 and 200 are x and y postions to scroll


3. Get No of CheckBoxes Checked/Unchecked
  1. selenium.getXpathCount("//input[@type='checkbox' and @checked]");
  2. selenium.getXpathCount("//input[@type='checkbox' and not(@checked)]");
    Also You can use like
    css=input[type=\"checkbox\"]:checked

4. Drop-down lists handling
To get selected value:
  1. selenium.isElementPresent("//select[@name='listbox']/option[contains(text(),'item2')]")
  2. selenium.getSelectedValue("name=listbox");

To get list items:
String[] items = selenium.getSelectOptions("name=listbox");


To set or select a item on dropdown:
selenium.select("listbox""label=item1");         //For Simple Select List

There is a select list, which contains a text box and down arrow image button. Clicking on button image, opens a drop down which contains element with dynamic id's.
Dynamic elements are : drop down elements (div's) , and image button.
This can be done by 
selenium.click("//input[@id='listbox']/following-sibling::img");
This clicks on image. Now we need to select the dropdown list element, which also has dynamic id.
So, I have used text function as,
selenium.click("//div[text()='item1']");            //which clicks on "item1" in the drop-down list.
Also have a look at this link Select an option from an ExtJS ComboBox


5. HTTP to HTTPS problems
http://qaselenium.blogspot.com/2011/04/how-to-handle-https-and-security-popups.html

6. Locate Elements by position
If you have 2 buttons on a page. Both have same ID, type, and available attributes are same. How you will identify which element to click?. Here is the answer.

  1. //input[@id='button' and position()=1] OR //input[@id='button']  //1st button
  2. //input[@id='button' and position()=2]    //2nd button

7. XPath Type : Functions
Always we have chances to meet locator problems while elements with same attributes, ids, names, etc. These kind of scenarios can be solved by using below techniques. Normally we can use 4 ways to identify the elements.
1. String
2. Boolean
3. Number
4. Node-Set
Here they are,
  1. Node-Set: last(), position(), count(), id(), local-name(), namespace-uri(), name()
  2. String: string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(), normalize-space(), translate()
  3. Boolean: boolean(), not(), true(), false(), lang()
  4. Number: number(), sum(), floor(), ceiling(), round()
Here are some examples.
  1. selenium.click("xpath=(//input[@type='checkbox'])[last()]");
  2. selenium.click("xpath=(//input[@type='submit'])[last()-1]");
  3. selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");

Comments

Post a Comment

Popular posts from this blog

Some good Resources / Blogs / Sites for Selenium Users

Here I have listed out some good blogs and sites by extensive selenium automation users. Hope these will help you a lot. http://automationtricks.blogspot.com  - by NirajKumar http://www.theautomatedtester.co.uk/ http://testerinyou.blogspot.com   - by Naga/Mathu http://seleniumready.blogspot.com  - by Farheen Khan http://seleniumdeal.blogspot.com/  - Amit Vibhuti http://seleniumexamples.com/blog Sauce Labs and BrowserMob are companies doing cloud and extensive selenium automation services, products, etc http://saucelabs.com/blog http://blog.browsermob.com http://testingbot.com/ Cedric Beust -  creator of the TestNG Java testing framework. http://beust.com/weblog/ http://blog.reallysimplethoughts.com/  - by Samit Badle, Created many Selenium IDE Plug-Ins Available Colud Testing: 1. SauceLabs 2. Soasta 3. BrowserMob 4. CloudTesting.com  etc. Selenium Testing Products: 1. Twist by ThoughtWorks 2.  TestMaker by  PushToTest 3. Element34 company providi

Change IE Browser ZOOM settings

Lot of UI automation testers could have faced this problem as we could change the zoom settings while operating manually for our convenience and forgot to reset to 100%. But our QTP and some other related tools would operate the browser perfectly if browser zoom is 100%. So wee need to change the zoom before start to run the scripts. Its better to have a code snippet in our framework to change this zoom setting right? Here we go... 1. We can simply change the Registry values before Invoking IE Function  ChangeRegistry   Dim  objShell   Set  objShell =  CreateObject ( "WScript.Shell" )  objShell.RegWrite  "HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Zoom\ZoomFactor" ,  "100000" ,  "REG_DWORD"   Set  objShell =  Nothing End   Function This option is very useful. But in real time, lot of customers could have restricted write access to windows registry. So we can try other options. 2. Use IE COM object and Change

UFT - Take full page screenshot by scrolling the page

'######################################################################################## 'This is navigate through the full page and taking individual screenshot of visible area '######################################################################################## Function TakeScreenshot Dim intScrolls, intScroll, strScrollPos Set pgApp = Browser ( " " ) .Page ( " " ) intScrolls = Round ( pgApp . RunScript ( " document.documentElement.scrollHeight / (screen.height) " ) , 2 ) If intScrolls < 1 Then intScrolls = - 1 pgApp . RunScript " window.scrollTo(0, 0); " Wait 1 Browser ( " " ) .CaptureBitmap " C:\screenshot0.png " , True For intScroll = 0 To intScrolls If Environment . Value ( " Browser " ) = " CHROME " Then strScrollPos = " scrollY " Else strScrollPos = " document.documentElement.scrollTop " End If If p