Tuesday, August 18, 2015

Hints 1

String comparison should be done as equals instead of ==

For example

 if(sActionKeyword=="click_MyAccount") should be

if(sActionKeyword.equals("click_MyAccount")


Friday, May 29, 2015

Sample Javascript code in Selenium Web driver

How to use Java script executor

import org.openqa.selenium.JavascriptExecutor;

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);

//Alert
JavascriptExecutor js = (JavascriptExecutor)driver;
Js.executeScript("alert('hello world');");

//click a button
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", element);

//refresh browser window
JavascriptExecutor js = (JavascriptExecutor)driver;
driver.executeScript("history.go(0)");

//get innertext of the entire webpage in Selenium
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.documentElement.innerText;").toString();

//Title of our webpage
JavascriptExecutor js = (JavascriptExecutor)driver;
string sText =  js.executeScript("return document.title;").toString();

//Scroll on application using  Selenium
JavascriptExecutor js = (JavascriptExecutor)driver;
//Vertical scroll - down by 50  pixels
js.executeScript("window.scrollBy(0,50)");

//click on a SubMenu which is only visible on mouse hover on Menu
JavascriptExecutor js = (JavascriptExecutor)driver;
//Hover on Automation Menu on the MenuBar
js.executeScript("$('ul.menus.menu-secondary.sf-js-enabled.sub-menu li').hover()");


// navigate to different page using Javascript
JavascriptExecutor js = (JavascriptExecutor)driver;
//Navigate to new Page
js.executeScript("window.location = 'https://www.facebook.com/uftHelp'");



//hello World
WebDriver driver = new ChromeDriver();
if (driver instanceof JavascriptExecutor) {
 ((JavascriptExecutor) driver).executeScript("alert('hello world');");
}



Thursday, May 28, 2015

How to setup Logging for Selenium web driver script

1. Open http://logging.apache.org/

2. Open Apache log4j link

3. Download from left shoulder tab

4. Extract and add Log4j Jar to eclipse

5. Create log4j.xml in the root folder of the script

<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

<appender name="fileAppender" class="org.apache.log4j.FileAppender">

<param name="Threshold" value="INFO" />

<param name="File" value="logfile.log"/>

<layout class="org.apache.log4j.PatternLayout">

<param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n" />

</layout>

</appender>

<root>

<level value="INFO"/>

<appender-ref ref="fileAppender"/>

</root>

</log4j:configuration>

6. Use Log.info("New driver instantiated"); comments across your scripting

7. Import following packages into the script

import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

8. Update below code under class file
private static Logger Log = Logger.getLogger(MLPTweets.class.getName());

9. With main section set the log file config

DOMConfigurator.configure("log4j.xml");

10. Where ever log needed update the following command in Log.Info();

Log.info("Tweets Data file Opened");

11. After the execution, open the logfile.log from the base folder and verify

Tuesday, May 26, 2015

How to create new Maven project from eclipse

1. Eclipse-->File-->New -->Other-->Browse workspace-->Quick-start archetypes-->GroupId,ArtifactId(projectName)-->Update pom.xml with latest jnit version

2. Right click pom.xml and run as maven project

How to setup Maven for Selenium Webdriver

1. Open https://maven.apache.org/

2. Set the folder path D:\Selenium\Eclipse\Maven\apache-maven-3.0.5 at

3. Set the environment variable
  MAVEN_HOME
  D:\Selenium\Eclipse\Maven\apache-maven-3.0.5

4. Set System Environment Variable
JAVA_HOME
C:\Program Files\Java\jdk1.8.0_45

5. Edit Path Environment variable and add

6. Check Maven is installed in the computer or not
   a. open command prompt
   b. enter mvn --version
  it should dipslay the version of the maven installed


How to use read JSON objects/Values into selenium through Java

Step 1
1. Open Json file in JSON parser to identify the object array hierarchy
2. Associate java-json.jar file to the eclipse libraries
3. Paste the json content into the parser to figure out the hierarchy to access http://json.parser.online.fr/
4. The sample tweets are identified through text attribute
5. Go through the following code
Sample Code

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;



public class Test {
private static WebDriver driver = null;
public static void main(String[] args) throws IOException, InterruptedException{

driver = new FirefoxDriver();

driver.get("http://webapptoshowtweets/hilton");
Thread.sleep(10000);
Thread.sleep(5000);

try {

URL url = new URL("http://dallas/tweets.json");

URLConnection urlConnection = url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

BufferedReader r = new BufferedReader(new InputStreamReader(in));

StringBuilder total = new StringBuilder();

String line;

while ((line = r.readLine()) != null) {

total.append(line);

}

in.close();


JSONArray jsonArray = new JSONArray(total.toString());

String[] values=new String[jsonArray.length()];
//System.out.println("Total Tweets: " + jsonArray.length());
for (int index = 0; index < jsonArray.length(); index++) {

JSONObject jsonObject=jsonArray.getJSONObject(index);

String text=jsonObject.getString("text");

String strActTweetDesc = driver.findElement(By.id("tweetsDescription")).getText();

if(strActTweetDesc.equals(text)){
System.out.println("String Matches: Passed" + text);
}
else
{
System.out.println("Tweet Fails");
System.out.println("Expected String: " +text);
System.out.println("Actual Tweet String: " +strActTweetDesc);
}

//Click Next Button
//Selenium get Div Element
//WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > #tweetsContainer > #tweetsDescription"));
WebElement btnTweetNext = driver.findElement(By.cssSelector("#tweets > a > div"));
//*[@id="tweets"]/a/div

btnTweetNext.click();
Thread.sleep(1000);

values[index]=text;
//System.out.println(text);


} // for to navigate Json data



} catch (JSONException e) {

e.printStackTrace();

}

}


}

Monday, May 18, 2015

Set Value to Select Area object

<td>
<input id="txtEditCampaignId-1513" value="" type="hidden">
<textarea id="txtCampaignName-1513" style="width:350px;height:100px"></textarea>
</td>

The following code identifies text area element and sets value to it.

WebElement CmpTxtArea = driver.findElement(By.xpath("//*[starts-with(@id,'txtCampaignName')]"));
CmpTxtArea.sendKeys("Text Area Success");


How to handle the element when Id changes dynamically at the End





driver.findElement(By.cssSelector("button[id^='btnCreateNewCampaign']")).click();



Similarly

driver.findElement(By.cssSelector(“button[id^=’finish’][id$=’_NS_’]”));

it uses the regular expression with CSS  Selector where id^ looks for the word starting with finish and ends with _NS_.

How to click checkbox/link from a WebTable where Table id is unknown in a web page


//Select Link Object
List<WebElement> MainTables = driver.findElements(By.tagName("table"));

int i_TblCount = 0;
String strProjectName = "TestAutomation6";
String strActualProjName;
for (WebElement TblPosition:MainTables)
{
String strText;
strText = TblPosition.getText().trim();

if(strText.startsWith("+ Restructure Opportunities"))
{

System.out.println(strText);
System.out.println(" | ");
List<WebElement> tblPosition1 = TblPosition.findElements(By.tagName("table"));
System.out.println("Tables within Restructure Opp" + tblPosition1.get(1).getText());

List<WebElement> trows = tblPosition1.get(1).findElements(By.tagName("tr"));
for( WebElement TblRow:trows)
{
System.out.println(TblRow.getText());
List<WebElement> tds = TblRow.findElements(By.tagName("td"));
if(tds.size()>2){
strActualProjName = tds.get(1).getText();
System.out.println(strActualProjName);
if(strProjectName.equals(strActualProjName))
  {
//tds.get(0).click();
  //String strtdtext = tds.get(0).findElement(By.tagName("input")).getAttribute("innerhtml");
  //CheckBox
  tds.get(0).findElement(By.tagName("input")).click();
  //tds.get(1).findElement(By.tagName("a")).click();
  String s = tds.get(1).findElement(By.tagName("a")).getText();
  tds.get(1).findElement(By.tagName("a")).click();
  //tds.get(1).findElement(By.linkText(strActualProjName)).click();
  System.out.println(s);
  Thread.sleep(4000);
  driver.findElement(By.linkText("Campaigns")).click();
  Thread.sleep(4000);
  break;
} //If Project Name found in the List

 }//if tds.size

} //For to find Project List Table

}// If table starts with Restructure Opportunities

}//All Table For Loop

Sunday, May 10, 2015

How to fix Eclipse starting Error that returns Java was started but returned exit code = 1

If eclipse couldn't be opened and returns the error message as Java was started but returned exit code = 1




1. Uninstall all the existing java applications
2. Install JDK 8 64 bit based on your windows os
 a. Search JDK 8 64 bit in chrome
 b. Open the first result on oracle site
 c. Under Java SE Development Kit 8u45 select windows *64 link and download it.
 d. Open and Install it
3. The path installed on program files installed should set path default to it. Click open eclipse now, it should open successfully.

If again the same issue exist, open eclipse.ini file and update the -vm C:\Program Files\Java\jdk1.8.0_45\bin\javaw.exe

Save and open eclipse, it should open successfully.


Friday, May 8, 2015

Selecting sub menu while mouse hover top menu

In the above image Tools menu needs to be selected first and then sub menu should be selected.  In selenium webdriver the following package needs to be imported to use class Actions.

Use this class rather than using the Keyboard or Mouse directly. Implements the builder pattern: Builds a CompositeAction containing all actions specified by the method calls.

Pls. refer  http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/interactions/Actions.html for action class methods and constructors.

To implement Actions class, the following package needs to be imported

import org.openqa.selenium.interactions.Actions;

linkText method of findElement method directly gets the link which has innerText within it. The below code can select the sub menu item.


Actions action = new Actions(driver);

WebElement mnuTools = driver.findElement(By.linkText("Tools"));

action.moveToElement(mnuTools).build().perform();

driver.findElement(By.linkText("Ad Copy Manager Internal")).click();