Saturday 23 January 2016

Getting Error Message : java.util.regex.PatternSyntaxException: Unclosed character class near index 0

While try to split the value by using "[" OR "]" then we are getting the above issue.


Ex : String str="Selenium []"
    str.split("[")

we are getting the below exception.


Exception :

java.util.regex.PatternSyntaxException: Unclosed character class near index 0


Solution

The Special character "["  and "]" used in Regular Experssions, so these characters are not standared characters.

So we should add excape character for use this special character ("\[" and "\]"). But the escape character "\" is not allowed for "["  and "]".

So we should use string as "\\[" or "\\]"


Exact code will be

Ex : String str="Selenium []"
    str.split("\\[")


http://stackoverflow.com/questions/21816788/unclosed-character-class-error

Getting Error Message : Access restriction: The type Provider is not accessible due to restriction on required library C:\Program Files\Java\jre8\lib\jsse.jar




Solution


Go to the Build Path settings in the project properties.
Remove the JRE System Library
Add it back; Select "Add Library" and select the JRE System Library. The default worked for me.


Reason :


This works because you have multiple classes in different jar files. Removing and re-adding the JRE lib will make the right classes be first. If you want a fundamental solution make sure you exclude the jar files with the same classes.

Getting Error Message : org.openqa.selenium.firefox.NotConnectedException: Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms.


Reason :

While launching Mozilla browser getting the exception


Solution:

There are two possibility for above exception

1) Mozilla browser compatibility issue

2) We may configure many version of selenium jar files in build path. So remove all jar files from configure build path and update the latest jar files.

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric formula cell



Reason :
If we read string value from Formula cell then we are getting this exception.


Solution:

Use string value in cell.

Getting Error Message : java.lang.IllegalStateException: Cannot get a text value from a numeric cell



Reason:

If we read string value from integer cell then we are getting this exception.






Solution :



Use String data in Excel

Or

Add (') in front of integer then its considered as string while reading the data from cell.



How to Enter User id and Password in Authentication window using Robot Class in selenium



We can use Robot class or AutoIT tool for enter user id and password in Authetication window using selenium


Using Robot Class
----------------


fd.get("https://www.google.co.in");
driver.findElement(By.name("btnK")).click()
       
        Thread.sleep(5000);
        Robot rb = new Robot();

        //Enter user name by ctrl-v
        StringSelection username = new StringSelection("username");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);           
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_CONTROL);

        //tab to password entry field
        rb.keyPress(KeyEvent.VK_TAB);
        rb.keyRelease(KeyEvent.VK_TAB);
        Thread.sleep(2000);

        //Enter password by ctrl-v
        StringSelection pwd = new StringSelection("password");
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
        rb.keyPress(KeyEvent.VK_CONTROL);
        rb.keyPress(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_V);
        rb.keyRelease(KeyEvent.VK_CONTROL);

        //press enter
        rb.keyPress(KeyEvent.VK_ENTER);
        rb.keyRelease(KeyEvent.VK_ENTER);

        //wait
        Thread.sleep(5000);
       

How to enter the value to text box and select from suggestion drop down box


Consider the below example


Ex: https://www.google.co.in


While try to enter the any string in  google text box for searching, we are getting the suggestion drop down box. Here we need to select the value from drop down box and click search button.

use below lines of code

driver.findElement(By.id("gs_htif0)).sendKeys("Selenium Automation"+"\n");



Here, sendKeys("Selenium Automation"+"\n")

we should use "\n" for handle this issue. Its used for send the ENTER keys for click the button.

How to Write data into .xlsx excel file format file by using Apache POI file



public void WriteExcel(String FilePath,String SheetName,int row,int col,String data) throws IOException,FileNotFoundException
    { 
       
            FileInputStream fsIP= new FileInputStream(new File(FilePath)); //Read the spreadsheet that needs to be updated
            XSSFWorkbook wb = new XSSFWorkbook(fsIP); //Access the workbook
            XSSFSheet worksheet = wb.getSheet(SheetName); //Access the worksheet, so that we can update / modify it.
//            int rowcount=worksheet.getLastRowNum();//return row count
                    
//            HSSFRow row1 = worksheet.createRow(row);
            XSSFRow row1 = worksheet.getRow(row);
            XSSFCell cell = row1.createCell((short) col); //Create a new cell in current row
            cell.setCellValue(data);  //Set value to new value
            fsIP.close(); //Close the InputStream
       
            FileOutputStream output_file =new FileOutputStream(new File(FilePath));  //Open FileOutputStream to write updates
            wb.write(output_file); //write changes
            output_file.close();  //close the stream  
    }

Difference between toString() and getStringCellValue in Apachi POI




1) toString()

Its returns the string object.

If excel have the below data type variable then it returns the below corresponding values


-> IF String - Return String
-> IF Integer - Return Integer
-> If Date - Return Date
-> If Formula - Return formula (Not return value after formula get executed)



2) getStringCellValue()

Its return the string value if the cells contains only string, Other wise its returns exception.


If excel have the below data type variable then it returns the below corresponding values


-> IF String - Return String
-> IF Integer - Return IllegalStateException (Use getNumericCellValue )
-> If Date - Return IllegalStateException (Use getDateCellValue())
-> If Formula - Return IllegalStateException (Use getCellFormula and getCachedFormulaResultType)

How to Reading Formula string from excel sheet using Apache POI

How to read String,Integer,Formula Value from excel sheet(.xlsx) using Apache POI




The Apache stores two value for formula cells.

1) Retrive the Formula value (Only Formula, Not String)   - getCellFormula()
2) Retrive the string after formula got executed (Only string, NOT formula) - getCachedFormulaResultType()


So Normally we are using getCachedFormulaResultType() for retrive the strings from excel after formula get execute.


public String findValueOfTestDataFromExcel(String FilePath,String SheetName,int row,String Text) throws IOException

    {
        String str1="";
        String str2 = "";
        Double val;
        Date date1;
        FileInputStream file2=new FileInputStream(FilePath);
        XSSFWorkbook book2 = new XSSFWorkbook(file2);
        XSSFSheet sheet2 = book2.getSheet(SheetName);
       
        int col=sheet2.getRow(row).getLastCellNum();
        for(int i=0;i<=col;i++)
        {
            str1=sheet2.getRow(row).getCell(i).toString();
            if(str1.contains(Text))
            {
               
                    switch(sheet2.getRow(row).getCell(i).getCellType())
                    {
                    case Cell.CELL_TYPE_STRING:
                        str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        val=sheet2.getRow(row).getCell(i).getNumericCellValue();
                        str2=String.valueOf(Math.round(val));
                        break;
                    case Cell.CELL_TYPE_FORMULA:
//                        str2=sheet2.getRow(row).getCell(i).getCellFormula();   //Get formula
                        switch(sheet2.getRow(row).getCell(i).getCachedFormulaResultType())
                        {
                        case Cell.CELL_TYPE_STRING:
                            str2=sheet2.getRow(row).getCell(i).getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            date1=sheet2.getRow(row).getCell(i).getDateCellValue();
                            SimpleDateFormat sdf2=new SimpleDateFormat("MM'/'dd'/'yyy");
                            str2=sdf2.format(date1);
                            break;
                        }
                        break;
                   
                    }
                   
                break;           
           
            }
               
        }
        return str2;
    }
   

How to print the all value from drop down box in selenium




By using ID:

List<WebElement> allText=new Select(driver1.findElement(By.id(getId("ID1")))).getOptions();
int i=0;
for(webElement ele:allText)
{
System.out.println(ele.get(i).getText());
i++;
}



By using xpath :


List<WebElement> allText = driver.findElements(By.xpath("//*[@id="vehicleTypeName"]/option"));
int i=0;
for(webElement ele:allText)
{
System.out.println(ele.get(i).getText());
i++;
}

How to get column number from excel sheet using apache poi

We can get column number by using below different options






Option1:
int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();
or


Option2 :
int noOfColumns = sh.getRow(0).getLastCellNum();


There is some difference between above two options

Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Getting Error Message : org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]


Reason :

 If we are using xls format excel file for reading/writing by using XSSF apachi poi then we will get this issue

Solution :

XSSF used only for XLSX excel file format only.
HSSF used only for XLS excel file format only










So we will use xls format excel file for reading/writing by using HSSF apachi poi for avoiding this issue.

XML Notes


XML = Extensive Markup Language

Consider below example


<bookstore>
  <book category="children">
    <title>Harry Potter</title>
    <author>J K. Rowling</author>
    <year>2005</year>
    <price>29.99</price>
  </book>
  <book category="web">
    <title>Learning XML</title>
    <author>Erik T. Ray</author>
    <year>2003</year>
    <price>39.95</price>
  </book>


 <table>
    <td>Apples</td>
    <td>Bananas</td>
   <table>

 <h:table xmlns:h="http://www.w3.org/TR/html4/">
  <h:tr>
    <h:td>Apples</h:td>
    <h:td>Bananas</h:td>
  </h:table>

</bookstore>



Here,

1) Element = All the item with in <> is called Element

2) Attribute = Element may have the Attribute. Its contain data related to specifi element. Ex: "Category" is Attribut.

3) Attribute Value = Attribute have the value. Here, "children" is value of "Category" attribute. Here Attribute value should be with in double quotes.

4) NameSpace =
Its used to avoid Element Name conflicts.
So we add any prefix for differentiate the Same element name that is called Namespace.
The Namespace can be defined by an "xmlns" attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.


Ex: Here xmlns:h="http://www.w3.org/TR/html4/" is namespace declaration and h is prefix of the element for diffrentiate the same element name.
Here the <table> element have duplicated. So we are using namespace and add the prefix for differntiate and declare for different meaning.

Xpath Axes


Context Node:

Context node is start node in xpath

Ex :

URL = https://login.yahoo.com/
XPath = //input[@id='login-passwd']/following::input


Here

input[@id='login-passwd']  is context node.



There are following XPath Axes are available


1. Child Axes

Its identify the child node of the context node.

Ex:

URL = http://www.w3schools.com/xml/default.asp
XPath = //div[@id='leftmenu']/child::*
Output = Its identify the child node(<div id="leftmenuinner") of the context node (div id="leftmenu").


2. Parent Axes

Its identify the parent node of context node.

Ex:

URL = http://www.w3schools.com/xml/default.asp
XPath = //div[@id='leftmenu']/parent::*
Output = Its identify the parent node(<div id="belowtopnav") of the context node (div id="leftmenu").


3. Following Axes

Its identify the all node which is immediately match after current context node.

Ex:

URL = https://login.yahoo.com/

Xpath = //input[@id='login-passwd']/following::input

Output = Returns 7 immediate matching node after current context node.So it wont see any node, it will return all immediate matching node.


4. Following Sibling Axes

Its return the all node which is immediately match after context node under same parent node (Return sibling node only)

Ex:

URL = http://www.w3schools.com/xml/default.asp

Xpath= //a[contains(.,'XML Namespaces')]/following-sibling::a

Output =  Returns 8 immediate matching node after current context node. So it will see the parent node (<div>) and returns the only matching sibling nodes.


5. Preceding Axes

Its Identify the all node which is immediately match with before current context node.

Preceding Axes is opposite of Following Axes.


Ex:

URL = https://login.yahoo.com/

.//*[@id='login-signin']/preceding::input

Output = Returns 3 immediate matching node before current context node. So it wont see any node, it will return all immediate matching node.


6. Preceding Sibling Axes

Its return the all node which is immediately match before context node under same parent node (Return sibling node only)

Ex:

URL = http://www.w3schools.com/xml/default.asp

Xpath=//a[contains(.,'XML Namespaces')]/preceding-sibling::a

Output =  Returns 8 immediate matching node before current context node. So it will see the parent node (<div>) and returns the only matching sibling nodes.

What is Absolute Path and Relative Path in xpath

-> XPath is designed to allow the naviagtion of XML documents.

-> The main purpose of Xpath is selecting individual elements, attributes or some other part of XML documents.


Absolute XPath

Absolute XPath starts with the root node or a forward slash (/).
The advantage of using absolute is, it identifies the element very fast.
Disadvantage here is, if any thing goes wrong or some other tag added in between, then this path will no longer works.

Example:
If the Path we defined as
1. html/head/body/table/tbody/tr/th

If there is a tag that has added between body and table as below
2. html/head/body/form/table/tbody/tr/th

The first path will not work as 'form' tag added in between


Relative Xpath

A relative xpath is one where the path starts from the node of your choise - it doesn't need to start from the root node.

It starts with Double forward slash(//)

Syntax:
//table/tbody/tr/th

Advantage of using relative xpath is, you don't need to mention the long xpath, you can start from the middle or in between.

Disadvantage here is, it will take more time in identifying the element as we specify the partial path not (exact path).

If there are multiple elements for the same path, it will select the first element that is identified

Selenium TestNG Parallel Testing


We can launch the N number of browser at a time, then we can run our test in each and every browser at a same time.

we need to configure xml file alone

<Suite name="Suite" parallel="tests" thread-count="3">

<test name="test1">
    <classes>
        <class name="driverFiles.TestNGExecution"></class>
        <methods>
            <include name="TC_01"> </include>
        </methods>
           
    </classes>
   
</test>

<test name="test1">
    <classes>
        <class name="driverFiles.TestNGExecution"></class>
        <methods>
            <include name="TC_01"> </include>
        </methods>
           
    </classes>
   
</test>

<test name="test1">
    <classes>
        <class name="driverFiles.TestNGExecution"></class>
        <methods>
            <include name="TC_01"> </include>
        </methods>
           
    </classes>
   
</test>

</Suite>




From above XML file

1) parallel="tests"  = this we mentioned as create instanace as every test and run browser.

2) thread-count="2"  = its launch the two browser and run two test first. Then third test will execute. If we mention thread-count="3", then its open three browser and run all three tests.

3) We need to create seperate tests.

4) It will take some time from first browser launch time to second browser launch time. if our test steps low means we unable to see the all browser lauch. So its better to have the more lines of code to see the different browser launch at a same time.

Getting Error Message : f.QueryInterface is not a function Command duration or timeout: 63 milliseconds

While launch the URL in Mozilla Firefox getting below error

URL = https://www.google.co.in

Error Desc : f.QueryInterface is not a function Command duration or timeout: 63 milliseconds


Solution 1:

if the URL is not contais http:// or https:// then we get this kind of error message.

Wrong code: URL = www.google.co.in

Correct code: URL = https://www.google.co.in



Solution 2 :


Just remove the quotes for the URL and it will work fine.

If the URL have any double quotes in configuration file or excel file then we are getting this kind of error message

Wrong code: URL = "https://www.google.co.in" (In excel of configuraion file)

Correct code: URL = https://www.google.co.in

Getting Error Message : String index out of range: -17

Reason:

IF we run the Execution by using existing excel then it may get chance is not accessible by selenium. So we will get the error like below

Error Desc : String index out of range: -17


Solution :

1) Create New Sheet2
2) Copy all content from old sheet to new sheet.
3) Now its readable by selenium

Getting Error Message : org.openqa.selenium.ElementNotVisibleException: Element is not displayed



Reason : The object is not visble, so its throws this exception in ie (Even if its display in IE). So we need to make it display before run script.

Solution:





Selenium determines an element is visible or not by the following criteria (use a DOM inspector to determine what css applies to your element, make sure you look at computed style):

visibility != hidden
display != none (is also checked against every parent element)
opacity != 0 (this is not checked for clicking an element)
height and width are both > 0
for an input, the attribute type != hidden

Your element is matching one of those criteria. If you do not have the ability to change the styling of the element, here is how you can forcefully do it with javascript.

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", inputElement);

or

jse.executeScript("document.getElementById('mini-7').setAttribute('checked', 'true');");





Getting Error Message : org.openqa.selenium.WebDriverException: JavaScript error



Reason :We are getting this exception because if any timeout issue for run java script executor.

Solution :
driver.manage().timeouts().setScriptTimeout(30, TimeUnit.SECONDS)

Getting Error Message : org.openqa.selenium.InvalidElementStateException: Element must not be hidden, disabled or read-only



Reason : if object hidden, then webdriven unable to enter the text. so we need to enable the text by using javascriptexecutor, then will enter the script

Solution :

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('mini-7').setAttribute('type', 'text');");
driver.findElement(By.cssSelector("#mini-7 > input.mini-textbox-input")).clear();
driver.findElement(By.cssSelector("#mini-7 > input.mini-textbox-input")).sendKeys("yy");

Getting Config Build Path Error in Eclipse indigo (Java 8)




We are getting the below two error while configure the build path

1) The project was not built since its build path is incomplete. Cannot find the class file for java.util.Map$Entry. Fix the build path then try building this project.

2) The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files.



Solution :

Please check the our eclipse version is support the Java 8 or not.

Eclipse Kepler and Luna versions are have in built Java 8 version. So we can use these Eclipse version for Java 8.

How to search the string in perticular excel sheet using Apche POI



    public int findString(String FilePath,String SheetName,String Text) throws IOException
    {
        FileInputStream fsIP= new FileInputStream(new File(FilePath));
        HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook
//        HSSFSheet worksheet = wb.getSheet("TestData"); //Access the worksheet, so that we can update / modify it.
        HSSFSheet worksheet = wb.getSheet(SheetName);
       
          for (Row row : worksheet) {
              for (Cell cell : row) {
                  if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                      if (cell.getRichStringCellValue().getString().trim().equals(Text)) {
                          return row.getRowNum();
                       
                      }
                  }
              }
          }
        return 0;
                    
     
    }
   


Note : Please use latest Apache POI for using this code or use Apache poi files which are supports all predefined functions.

How to run Selenium TestNg from QC




We can run the TestNg from QC by using below methods

1) Create the batch file(.bat) for run Selenium from TestNg.xml

2) Create the vapi-xp-test for run batch file.





1) Create the batch file(.bat) for run Selenium from TestNg.xml


-> create the folder name as "lib" and paste all .jar file need for run our selenium scripts.

Ex: create bin folder in below path

 C:\SeleniumTestNG\lib

And paste all jar files for Selenium,JXL,Apache POI etc.


-> create the batch file (.bat) like below and save as name TestNG.bat under C:\SeleniumTestNG path


set javaTestProjectPath=C:\SeleniumTestNG
c:
cd %javaTestProjectPath%
set path=C:\Program Files\Java\jdk1.8.0\bin
set classpath=%javaTestProjectPath%\bin;%javaTestProjectPath%\Lib\*;
javac -verbose %javaTestProjectPath%\src\driverFiles\TestNGExecution.java -d %javaTestProjectPath%\bin
java org.testng.TestNG %javaTestProjectPath%\testng.xml


Walkthru above code

-> set javaTestProjectPath=C:\SeleniumTestNG

set selenium project parent folder. we have all files inside the C:\SeleniumTestNG


-> c:
cd %javaTestProjectPath%

change the current project path in command prombt at run time.



-> set path=C:\Program Files\Java\jdk1.8.0\bin

set the path of Jave JDK



-> javac -verbose %javaTestProjectPath%\src\driverFiles\TestNGExecution.java -d %javaTestProjectPath%\bin


Here TestNGExecution.java is main file which we write all testNG annotations script.


%javaTestProjectPath%\bin  = its have all source code of the java file.



-> java org.testng.TestNG %javaTestProjectPath%\testng.xml


this code for running the testng.xml file from command probt.


-> SO now while double click on TestNG.bat under C:\SeleniumTestNG path, its automatically lauch the browser and run the selenium Automation script.





2) Create the vapi-xp-test for run batch file.


use this link -> http://www.ranorex.com/blog/running-ranorex-automated-tests-with-hp-quality-center

please use below method for Create the vapi-xp-test for run batch file.


-> Create the new Test (Testing-> TestPlan-> New Test)

-> Set the test type to “VAPI-XP-TEST:

-> Select VBScript as Script language:

-> Set “Console Application as test type:


-> Enter the batch file location in “Application Executable file” and press the “+” button to add the application call to your script:


-> Finish the HP VAPI-XP Wizard:



3) Run the Selenium TestNG from ALM

please use below method for run selenium TestNg from ALM QC


-> Selenium Test from TestPlan (Testing -> TestPlan -> test)

How to run TestNG using batch file



We can run the selenium TestNg framework by using command prompt. Also we can run the Selenium TestNG by using batch file (.bat).

From this approach we no need to open the Eclipse. We can run the script by double click on the batch file. Then its automatically get run.


Follow the below steps for run TestNG from batch file

For Ex: Consider the project path will be

E:\SeleniumTestNG

1) Create the folder with the name of "lib" and paste all required .jar files needs to be run Selenium script(include all selenium required jar files).


2) Create Run.bat batch file under same project path with below code

set javaTestProjectPath=E:\SeleniumTestNG
E:
cd %javaTestProjectPath%
set path=C:\Program Files\Java\jdk1.8.0\bin
set classpath=%javaTestProjectPath%\bin;%javaTestProjectPath%\Lib\*;
javac -verbose %javaTestProjectPath%\src\driverFiles\TestNGExecution.java -d %javaTestProjectPath%\bin
java org.testng.TestNG %javaTestProjectPath%\testng.xml

Here TestNGExecution.java file contains the main TestNg annotations code.

we can run above same code in command line also.

3) Once we double click on Run.bat file in project path, then its starts the automation execution.





How to install TestNG offline



please follow below method for install TestNg in offline.

->we should to use dropins folder for testNg offline installation. And make sure eclipse should close.

Ex: C:\eclipse Kepler\dropins\

-> download the testng-eclipse-5.11.0.28.zip plugins from this link -> https://developer.jboss.org/wiki/HowDoIInstallTheTestNG511EclipsePlugin

-> Unzip those file and we can see the files like below
plugins/org.testng.eclipse_5.11.0.28.jar


-> And create folder in dropins like below and paste those Jar file.

C:\eclipse Kepler\dropins\testng-eclipse-5.11\eclipse\plugins/org.testng.eclipse_5.11.0.28.jar


-> Launch the Eclipse now.

-> The TestNG plugin installed in offline now.

-> We can verify like Window -> Show View-> Other -> Java -> TestNg (Its added newly)


This is the steps for install TestNG offline

https://developer.jboss.org/wiki/HowDoIInstallTheTestNG511EclipsePlugin

Saturday 2 January 2016

Selenium Chrome Browser Automation issue solution




Reciving Error Message like "you are using an unsupported command line flag: ignore certificate errors stability and security will suffer" while automte the chrome browser using selenium


Solution


use below lines of code to solve this issue



System.setProperty("webdriver.chrome.driver","<<your chrome path>>");
    // To remove message "You are using an unsupported command-line flag: --ignore-certificate-errors.
    // Stability and security will suffer."
    // Add an argument 'test-type'
    DesiredCapabilities capabilities = DesiredCapabilities.chrome();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("test-type");
    capabilities.setCapability("chrome.binary","<<your chrome path>>");
    capabilities.setCapability(ChromeOptions.CAPABILITY, options);

    driver = new ChromeDriver(capabilities);


link -> http://stackoverflow.com/questions/23771922/protractor-error-message-unsupported-command-line-flag-in-chrome/23816922#23816922


********************************************************************************

Time out Exception receiving message from the renderer or chrome is not working properly
------------------------------------------------------------------------------------

Solution

Please comment below lines of code to resolve this issue

//driver.manage().timeouts().implicitlyWait(2000, TimeUnit.MILLISECONDS);
//driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
//driver.manage().timeouts().setScriptTimeout(60, TimeUnit.SECONDS);

Selenium - Error Message "The method sendKeys(CharSequence[]) in the type WebElement is not applicable for the arguments" while use SendKeys() method


We are getting the below error message while use SendKeys() method

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

Solution :

We got this error while we setup the project incorrectly. please follow below steps for resolve this issue

1) Change your compiler compliance level from 1.4 to 1.7.

Follow these steps in your eclipse:

Right click on your java project and select Build Path -> Click on
Configure Build Path...
In project properties window, Click/select Java Compiler at the left
panel
At the right panel, change the Compiler compliance level from 1.4 to 1.7
(Select which is higher version in your eclipse)
Lastly Click on Apply and OK
Now check your code. it will never show the same error...



or

2?) Set the JRE System Library again. If you use eclipse follow the steps below:

Go to project properties
Select Java Build Path at the left panel -> Select Libraries tab at the right
Click/select JRE System Library[] -> Click Edit button at the right side
Set your preferred JRE and click Finish button
Lastly click OK button from the project properties pop up window
Instead of editing you can also do by deleting and adding. The steps are:

Right-click on project » Properties » Java Build Path
Select Libraries tab
Find the JRE System Library and remove it
Click Add Library... button at right side » Add the JRE System Library (Workspace default JRE)


Refer = http://stackoverflow.com/questions/23485363/the-method-sendkeyscharsequence-in-the-type-webelement-is-not-applicable-for

How to set Break point and Debug in Eclipse


Breakpoint in Eclipse/Selenium


Breakpoint
-> By double click on left side, then we create breakpoints.

Conditional Breakpoint
-> Sometime we need breakpoint, if only some Conditions like Errors and exception. For that we can conditional breakpoint.
-> Right click on crated breakpoint -> Breakpoint Properties


*****************************************


Debug in Eclipse/Selenium




    F5 – Step Into
    F6 – Step Over
    F7 – Step Return
    F8 – Run until next breakpoint is reached

Table 1. Debugging key bindings / shortcuts
Key  Description
F5  Executes the currently selected line and goes to the next line in your program. If the selected line is a method call the debugger steps into the associated code.
F6  F6 steps over the call, i.e. it executes a method without stepping into it in the debugger.
F7  F7 steps out to the caller of the currently executed method. This finishes the execution of the current method and returns to the caller of this method.
F8  F8 tells the Eclipse debugger to resume the execution of the program code until is reaches the next breakpoint or watchpoint.

How to Highlight Web Element in Selenium






JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].style.border='2px groove green'", element);

js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: Red; border: 2px dotted solid green;");




For Red

js.executeScript("arguments[0].style.border='3px groove red'", element);
js.executeScript("arguments[0].style.border=''", element);



For Green


js.executeScript("arguments[0].style.border='3px groove green'", element);
js.executeScript("arguments[0].style.border=''", element);




js.executeScript("arguments[0].setAttribute('style', arguments[1]);",element, "color: red; border: 3px solid red;");



js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);",
element, "");


How to use Java script Executor in selenium




Create object for Java script executor and perform click,sendkeys method like below



JavascriptExecutor js = (JavascriptExecutor) driver1;

js.executeScript("document.getElementById('submit').click();");

js.executeScript("document.getElementById('gs_h0').value='Selenium';");

js.executeScript("$('#gs_h0').keyup();");



How to change object property value by using java script executor
----------------------------------------------------------------

Conside the below code

<input type="submit" jsaction="sf.chk" name="btnK" aria-label="Google Search" value="Google Search">


Here, we want to change the "value" property value from "Google Search" to "Yahoo Search" by using java script executor as per below


Code:


WebElement element = driver1.findElement(By.name("btnK"));
js.executeScript("arguments[0].setAttribute('value', 'Yahoo Search')",element);

How to run script from console (F12 - Devloper Tools) in mozilla firefox browser AND How to use Java script in selenium




we can run the selenium script in console then we can verify those results

-> Open the debloper tools in mozilla firefox by pressing "F12".

-> click "console", Here we can see the commands(run,clear,copy..) in right hand side.

-> Here we can type the code like below and click "Run" and verify the result,


For Click   = document.getElementById('submit').click();


For Enter Value  = document.getElementById('gs_h0').value='Selenium';


For Tab = $('#gs_htif0').keyup();


-> use below java script executor commands in selenium for above script


JavascriptExecutor js = (JavascriptExecutor) driver1;

js.executeScript("document.getElementById('submit').click();");

js.executeScript("document.getElementById('gs_h0').value='Selenium';");



js.executeScript("$('#gs_h0').keyup();");


Example


Object for drop down populated using java script



js.executeScript("$('#homeAddressZip').keyup();");


How to launch Mozilla or Chrome after setting System Property



Launch mozilla after set the system property


System.setProperty("WebDriver.firefox.bin", "<C:<\\Programfiles\\Mozilla Firefox\\firefox.exe>>");
FirefoxBinary binary = new FirefoxBinary(new File("C:/Program Files/Mozilla Firefox/firefox.exe"));
FirefoxProfile profile = new FirefoxProfile();






Launch the chrome after set below system property

System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\chromedriver.exe");
log.info("Selected browser is Chrome browser");

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.binary", "/usr/lib/chromium-browser/chromium-browser");

driver1 = new ChromeDriver(capabilities);

Selenium - Solution for click is not working properly in chrome


Please follow any one of method as mentioned below if click is not working properly in chrome


-> if click() method is not working, use sendkeys(Keys.Return)

driver1.findElement(By.xpath("//button")).sendKeys(Keys.RETURN);


->or use Action class as below

WebElement element = driver.findElement(By("element_path"));

Actions actions = new Actions(driver);

actions.moveToElement(element).click().perform():


-> or use java script as below

JavascriptExecutor jse = (JavascriptExecutor)driver;

jse.executeScript("scroll(250, 0)"); // if the element is on top.

jse.executeScript("scroll(0, 250)"); // if the element is on bottom.
or

JavascriptExecutor jse = (JavascriptExecutor)driver;

jse.executeScript("arguments[0].scrollIntoView()", Webelement);


Refer = http://stackoverflow.com/questions/11908249/debugging-element-is-not-clickable-at-point-error

difference between presenceOfElementLocated and visibilityOfElementLocated in Selenium




-> If use presenceOfElementLocated when you don't care whether if element visible or not, you just need to know if it's on the page

-> If use visibilityOfElementLocated when you need to find element which should be also visible

How to work with multiple window in selenium




We can handle the multiple window by using below methods


getWindowHandle = used to point to parent window. Its return String

getWindowHandles = Its have collection of window which present at a time. Its return collection of string.



Below code for working with multiple window


String ParentWindow=driver1.getWindowHandle();   
for(String windowpopup:driver1.getWindowHandles())
{
driver1.switchTo().window(windowpopup);
System.out.println("Title of the current window"+driver1.getTitle();

}

driver1.switchTo().window(ParentWindow);