Tuesday, March 15, 2016

Finding Text among the multiple
tags , that have same attributes around the page.


  • How to locate the element in web page that has common children and no unique attribute to identify.
    • Date: 3/15/2016
    • Ex: <div class="wrapper">Hi I am here</div> <div class ="Wrapper"> Hi I am there </div>.
      • Like this if we have multiple <div> in the page with same attribute class value Wrapper, how will you identify specific text from it. I know you could use [1] or [2].... based on the nth number of <div> tag but sometimes even that one will not work.
    • Have same scenario here:
      • Source: http://stackoverflow.com/questions/36018524/selenium-get-a-text-node-using-xpath-and-use-it-as-a-string-in-java/36020432#36020432
      • I have a section of code like this:
<div id='wrapper'>
  <span>*</span>   
  Question 1
</div>

      • I want to store the Question 1 as a string in Java so when I use the xpath //div/text() to get the text "Question 1." However when I try to print the value, I am getting the error Invalid Selector Exception Xpath //div/text() is: [object Text]. It should be an element.
String text = driver.findElement(By.xpath("//div")).getText();
//returns *Question 1
String text = driver.findElement(By.xpath("//div/text()")).getText();
//returns error

      • How am I supposed to store just the Question 1. I can replace the * once I get it using the first method above but I don't want to do that.
Ex1:


    • This is MSN website, here I would like to find out the text : Todd Palin in intensive care after snowmobile accident. How to find it, looks similar to the above scenario right because even this has code as below:
      • <img alt="In this file photo, former Alaska Gov. Sarah Palin of Alaska, Republican vice pr..." data-src="{&quot;default&quot;:&quot;//img-s-msn-com.akamaized.net/tenant/amp/entityid/BBqu9TY.img?h=75&amp;w=100&amp;m=6&amp;q=60&amp;u=t&amp;o=t&amp;l=f&amp;f=jpg&amp;x=524&amp;y=269&quot;}" src="http://img-s-msn-com.akamaized.net/tenant/amp/entityid/BBqu9TY.img?h=75&amp;w=100&amp;m=6&amp;q=60&amp;u=t&amp;o=t&amp;l=f&amp;f=jpg&amp;x=524&amp;y=269" title="todd palin - Andrew Harrer/Bloomberg News" class =" loaded" data-initial-set="true" width="100">
      • <span class="title">Todd Palin in intensive care after snowmobile accident</span>
      • Solution:
        • I’m not sure I know the best way to do this but this is a way. The issue is that you are looking for specific text within a group of elements that are children of the wrapper DIV. The only thing I can see in the example that you provided is that the text you want is outside of a containing tag. We can use that to our advantage. Basically the approach is to grab the entirety of the text inside wrapper and then loop through all child elements of wrapper removing the text contained within each from the original string. That should leave the text that you want. I have tested the code below using the example you provided.
String wrapperText = driver.findElement(By.id("wrapper")).getText().trim(); // get all the text under wrapper
List<WebElement> children = driver.findElements(By.cssSelector("#wrapper > *")); // get all the child elements of wrapper
for (WebElement child : children)
{
    String subText = child.getText(); // get the text from the child element
    wrapperText = wrapperText.replace(subText, "").trim(); // remove the child text from the wrapper text
}
System.out.println(wrapperText);



Jars and Difference between Selenium standalone server and Selenium-Java-Jar


http://stackoverflow.com/questions/36018648/selenium-standalone-server-and-selenium-java-jar-usage-specifics


The selenium standalone server contains everything i need to run my scripts on local machine or remote machine or Grid. I understand that it has both server side and client side bindings'.
If i use Selenium-Java-Jar, i can run scripts on my local machine. It has only client side bindings'. But again for Remote or grid i would need standalone server separately.
Considering all this why would i need to use Selenium-Java-Jar over selenium standalone server? Does it offer any thing good in terms of speed? What points scores over selenium standalone server for people to use Selenium-Java-Jar? Is it something to do with selenium standalone server supporting RC style scripts whereas Selenium-Java-Jar not supporting the same?



What are the Implementations differences between 'Selenium-server-standalone.jar' and 'Selenium Client & WebDriver'. Following is the link from SeleniumHQ.org website [http://www.seleniumhq.org/download/]..
  1. http://selenium-release.storage.googleapis.com/2.44/selenium-server-standalone-2.44.0.jar
  2. "http://selenium-release.storage.googleapis.com/2.44/selenium-java-2.44.0.zip"
I know first one is Formerly known as Selenium RC and second one is Selenium 2.0(Webdriver). But Is the latest version supporting all the jars in Webdriver in Selenium Server. I have only Selenium Server available, Did all the method's in Selenium Webdriver supports in Selenium Server? likewise, what are the differences between the jars in it?
Selenium WebDriver 2.0 - helps to write scripts for automating browsers..this package provides us with classes & methods to achieve automation. After writing scripts we can run them on LOCAL MACHINE and see automation ourselves. WebDriver projects were merged with selenium RC to overcome the drawbacks of selenium RC making it selenium WebDriver 2.0
Selenium Server: Now once i have my scripts (as mentioned above),To run scripts on REMOTE MACHINES (Test Beds) and NOT ON LOCAL MACHINE we do it using selenium server. So in short Selenium Webdriver works together with Selenium Server..they co-exist to help and not to replace each other.

Why importing Jar files:


To access selenium class functions like getTtile(), getText(), getAlert() or getConfirmation() etc.. we might need to import jar files.
We have library files in Jar fiiles that are embeded and put together so that the person who imports jar files, will be able to use the fuctions in the files direclty. Somelines public class files, If you import you could be able to use the methods(functions) of that class.


Scenario:

If you see that your script is not able to detect the inbuilt functions then it means you have not imported proper jar files( here in selenium we have only two already mentioned above jar files).




Friday, March 11, 2016

Selenium notes




1/11/2015:

Java

-        Child cannot have multiple parents. Means we cannot extend multiple classes, one class can extend only one class.

-        But Implementation could be done on multiple classes. This is called multiple inheritances.

-        Even Eclipse needs to have JDK(Java 1.7) installed and environment variable set before running code in java.

-        For Static methods memory is allocated during initialization. So memory gets allocated only once.

-        Passing parameters while creating object, is to call specific constructor (parameterized)

-        Initialize object – means

-        No limit for number of constructors

-        Local variables

-        Instance variable – memory loaded only when it is called not like static.

Can be declared along with static variables, this are the variables declared without static keyword

-        Class variables – cannot be declared inside methods?

-        Final class – cannot be inherited

Final method – cannot be overloaded

Final variable – cannot change the value of the variable

-        Abstract class -

-        Final abstract cannot be together for a class

-        This – keyword

It will pick up the current object value

-        Initialization and Instantiation ??

-        Super keyword – helps you to access  the methods of super class.

-        Override – is using same method names in parent and child, using the super keyword.

-        Adding jar files and importing packages… how are they different from each other.

Selenium

-        Selenium RC – we have to keep the server open - open the command prompt and run java commands to keep the server running

-        Selenium RC– does not interact with Windows application. Very difficult during windows authentication

-        Why do we need diff drivers while running code on diff browsers??

-        Only one limitation with webdriver is --- necessity of drivers(Server.exe) for all browsers except FireFox

-        Explicitwait – can be applied on web element, this is not for all elements but for a specific element. Like load to a button we use Explicit wait instead of Implicit wait.

Implicit wait - for all the components (exist in selenium IDE). It will wait for a mentioned time whatever be the web element.

 

-        Contains method of xpath is used vastly.

Xpath = “//input[contains(@src,’picture1’)]    ‘looks for word ‘picture1’ in the src property of that element, this helps to avoid using entire xpath

-        Why do we need to have two import statements here as they both talk about same thing:

Import org.openqa.selenium.*;

Import org.openqa.selenium.firefox.FirefoxDriver;

-        Why do we have this kind of object creation:

WebDriver obj1= new FirefoxDriver();

 

Instead of

WebDriver obj1 = new WebDriver(); --- which is wrong

              Solution:

              I don’t know why the above code is wrong, but when I looked at Select and List class, you might    understand.

            

-        Selenium does not detect Desktop applications, in this if any authentication error occurs while automating web application from desktop, then we need to use third party tools to continue or handle the desktop error.

-        Mozilla Firefox 41 does not support Selenium web driver

-        Driverobj.get and Driverobj.navigate.to ---- could be used for the same pupose but navigate has additional benefits like navigate used to navigate from the existing web page to other urls, forward or back the browser.

-        Sendkeys:

… here sendkeys could be used in diff ways 1. Enter value using keyword

.Sendkeys(“srikanth”)

2. Clicking enter or space etc  buttons

.Sendkeys(keys.Enter) – this one clicks enter button

 

-         

 

Xpath: 12/24/2013
-        Selenium 1 and Selenium2
-        Primary reason for selenium being so popular: Driving multiple browsers  and open source
-        We have 4 categories in selenium- Selenium IDE ,Selenium Remote Control(RC)(Selenium 1), Selenium Web Driver(Selenium 2) and Selenium Grid.
-        Selenium 2:
Selenium 1 is in intrusive in nature. If the field is not editable or not unable selenium 1 could not recognize (as it is purely javascript)
-        In case of Selenium 2, the handling each browser, each browser has got its own controls with selenium, this feature was not available in selenium 1.
-        Selenium locators:
-        Firefox = Firebug and IDE.
1.      Use Firebug to get the html code(id or class name of element) and IDE to evaluate whether that id or class belongs to the element in the web page. IF you give id value in the IDA and click find, it will highlight the corresponding element in the webpage.(this is one way to test Element locator)
2.      You can also test from console
-        Chrome= click F12 to see console.
Go to Element. Right click on element and select inspect element.
Click Escape or console. Here we can create query to test. Use this only when you are finding complex elements.
Syntax to test xpath: we use 2 functions:
Function1: $x(“<xpath>”) -> press enter. Ex: $x(“//input[…]”) ---here if you see after press enter, you could see the element html code or else o/p is just [].
Note: xpath is slower than id.
$x is the function to test xpath.
Function2:
-        // -anywhere/somewhere  in Html code (Relative path)
/- direct child
-        IE – IE Developer tool bar. Some applications may only open in IE, so lets use IE Developer tab for the same.
-        Id/name/class might be common across various elements, but xpath is not.  So use xpath as element locator in most of the cases.
-        $x(“//input[@id=’searchinput’][@idname=’search’]”)
-        $x(“//input[starts-with(@id=’searchinput’)]”)
-        $x(“//input[substring(@id.2)=’earchinput’]”)
-        $x(“//input[substring(@id. 2. 5)=’earch’]”)             // begin character length is ‘2’ and end character is ‘5’
-        Avoiding spaces:
$x(“//title[text()=’selenium – Google Search’]”)     //text() is used to get inner text
$x(“//title[normalize-space(text()=’selenium – Google Search’]”)       //if you have space at the beginning.
$x(“//title[normalize-space(text()=’selenium – Google Search’]”)      
-        ‘.’
-        $x(“//title[normalize-space(.)=’selenium – Google Search’]”)      
Here ‘.’ Identifies the present node, so you may not need to write text() always.
-        $x(“//title[contains(@id. ’hin’)]”)      
-        Xpath, we can navigate back, but this is not the case with css. So that is the reason css is faster than xpath.
-         

Timeouts:


-        Pageload Timeout = selenium will wait till page loads.
-        setScriptTimeout =
-        Explicit wait = specif point
-        Implicitwait= global value
-         


 

 

 
-        JavascriptExecutor: Specialized form of webdriver, it will let you to execute any javascript on the page.
-        Sometimes if you are not able to find element  you could use JavascriptExecutor.

 
-        Selenium does not allow you to reuse in existing session
-        Use Selenium discussion forum to get more details on selenium.
-        Work on scenarios: Get the details of more scenarios-
-       

-        Keys. Back Space – is used to provide keyboard keys to the selenium code. ‘Enter’ key.
-        driver.switchto() ---iframes, alerst, popus—we use this.
-        Driver.switchTo().frame.
-        selenium does not distinguish b/w new tab and new window.
-        .getwindowhandles()
-       

-       

 
-        Annotations
 
-        Assert text
 
-        Junit
 
-       

 
-       

 

 
-        Dataprovider – class using which we can get data from excel
-         

Selenium Methods Notes:


-        Selenium RC:

1.      Jason Huggins developed a Javascript library that could drive interactions with the page, allowing him to automatically rerun tests against multiple browsers.

2. Selenium tests can be written in any of following language: Java, C#, Python, Ruby, Perl and PHP

3. Selenium interacts with the UI elements of a web site using JavaScript injection

4. Limitation of Selenium RC

o   Restrictive to do different things due to the security limitations browsers apply to JavaScript (Uses JavaScript based automation engine)

o   Webapps became more and more powerful over time with special features and new browser support

-        WebDriver developed by Simon Stewart works by accessing the OS and passing commands to the browser from the OS. Not constrained by the JavaScript Sandbox as Selenium RC is.

-        To overcome limitation offered by Selenium RC and to support broader range of browsers Selenium RC and WebDriver is merged to form Selenium WebDriver.

-        The downside to Selenium WebDriver is that it requires new implementations for each of the browsers that it works against. This is due to each browser having its own access points with the Operating System.

-        WebDriver ’s goal is to provide a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

-        WebDriver  supports dynamic web pages where elements of a page may change without the page itself being reloaded

-        WebDriver Scripts can be written in any one of following languages: Java, C#, Perl, Python, Ruby, PHP.

-        Different types of WebDrivers: HtmlUnitDriver, FirefoxDriver , InternetExplorerDriver , ChromeDriver  and SafariDriver

-        WebDrivers available for Mobile testing include: AndriodDriver and IPhoneDriver

Name of driver
OS Supported
Class to instantiate
HtmlUnitDriver
All
org.openqa.selenium.htmlunit.HtmlUnitDriver
FirefoxDriver
All
org.openqa.selenium.firefox.FirefoxDriver
InternetExplorerDriver
Windows
org.openqa.selenium.ie.InternetExplorerDriver
ChromeDriver
All
org.openqa.selenium.chrome.ChromeDriver
SafariDriver
MAC
org.openqa.selenium.safari.SafariDriver

 

Name of driver
OS Supported
Class to instantiate
AndroidDriver
All
org.openqa.selenium.android.AndroidDriver
IPhoneDriver
All
org.openqa.selenium.iphone.IPhoneDriver

 

-        Emulating Specific Browser:

o   Using Browser Version

HtmlUnitDriver driver = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);

 

o   Using Capabilities

        HtmlUnitDriver driver = new HtmlUnitDriver(capabilities);

 

-         WebDriver pros and cons:

Pros:

        Fastest implementation of WebDriver

        A pure Java solution and so it is platform independent.

        Supports JavaScript

Cons:

        It's not graphical, which means that you can't watch what's happening

 

-        FireFoxDriver Instantiation process:

WebDriver  driver = new FirefoxDriver()

This will invoke firefox browser and returns an handle in form of WebDriver  object which is used to interact with the browser.

-        InternetExplorerDriver Instantiation process:

To work with IE, first download IEDriverServer.exe file from

http://code.google.com/p/chromedriver/downloads/list  and keep it is your project resources folder.

Set Webdriver.ie.driver  property

        System.setProperty("Webdriver.ie.driver","src/main/resources/drivers/ie/IEDriverServer.exe")

Ex:

System.setProperty("webdriver.chrome.driver", C:\\Users\\Public\\Jars\\ChromeDriver.exe");

WebDriver driver = new ChromeDriver();

      WebDriver  driver = new InternetExplorerDriver ()

 

-        Test can be executed against emulators and real devices for IPhone and Andorid OS.

IPhoneDriver Instantiation process

To work with Iphone, first do the setup as given in following page: http://code.google.com/p/selenium/wiki/IPhoneDriver.

Instantiate a WebDriver  implementation

  WebDriver  WebDriver  = new IPhoneDriver();

Andorid Instantiation process

To work with Andorid, first do the setup as given in following page: http://code.google.com/p/selenium/wiki/AndroidDriver.

Instantiate a WebDriver  implementation

        WebDriver  WebDriver  = new AndoridDriver();

-        Useful WebDriver Methods:

1.      get:

void get(java.lang.String url)

Load a new web page in the current browser window.

Parameters: url - The URL to load. It is best to use a fully qualified URL

Ex - WebDriver .get(“http://ww.google.com”);

2.      getTitle:

java.lang.String getTitle()

The title of the current page.

Returns: The title of the current page, with leading and trailing whitespace stripped, or null if one is not already set

Ex - WebDriver .getTitle( );

3.      close:

void close()

Close the current window, quitting the browser if it's the last window currently open.

Ex - WebDriver .close();

4.      quit:

void quit()

Quits this driver, closing every associated window.

Ex - WebDriver .quit( );

-        WebDriver – Browser Navigation Methods:

Method
Description
example
back()
Move back a single "item" in the browser's history.
Wedriver.navigate().back();
forward()
Move a single "item" forward in the browser's history.
Wedriver.navigate().forward();
refresh()
Refresh the current page
Wedriver.navigate().refresh();
to(java.lang.String url)
Load a new web page in the current browser window.
Wedriver.navigate().to (“http://www.cognizant.com”);

 

-        WebDriver Methods –  To switch between Windows:

Method
Description
example
java.util.Set<java.lang.String> getWindowHandles()
A set of window handles which can be used to iterate over all open windows.
Wedriver.getWindowHandles();
alert()
Switches to the currently active modal dialog for this particular driver instance.
Wedriver. switchTo().alert();
defaultContent()
Selects either the first frame on the page, or the main document when a page contains iframes.
Wedriver. switchTo() .defaultContent();
window(java.lang.String nameOrHandle)
Switch the focus of future commands for this driver to the window with the given name/handle.
Wedriver. switchTo(). window(“id”);

 

-