Tuesday, June 17, 2014

Selenium : WebDriver’s most popular / Basic Commands(important)


WebDriver’s most basic popular Commands
Sample :
https://www.cs.tut.fi/~jkorpela/www/testel.html
http://catchbug.blogspot.in/2014/08/basic-html.html
http://www.ironspider.ca/forms/checkradio.htm


Selenium important code snippets 




Element
Related
Handling parents
Misc Operations
Browsers
Special
File
operations
Framework
Is present
Window
Wait
Chrome
Action
Excel
stringutils.mid
build.gradle
Locators -8
Frame
Navigate
IE
Robot
TextFile
stringutils.indexof
testng.xml
Checkbox
Alert Box
keypress
Cookie
Javascript
screenshot
stringutils.leftpad
dataprovider
Radio





getcapabilities
POM (By)
Dropdown





desriedcapabilities
Softassert
tooltip









Search elements:
1. Try{
a. Driver.findElement(By.xpath(//dd/dd”)).click();
}catch(Exception e){System.out.print(“not present”);

2. If ( Driver.getpagesource().contains(“google search”) == true)

Locators:
1. Xpath
2. Css
3. Linktext
4. Id
5. Name
6. Partiallinktext
7. Tagname
8. ClassName

CheckBox
List<WebElement> eBoxes=driver.FindElements(By.xpath(//input[@type=’checkbox’]”));
For(int i=0;i<=eBoxes.size-1;i++) //for(WebElement w:eBoxes)
eBoxes.get(i).click(); //w.click();

/* Good to know : There is no difference between List and ArrayList in Java
List is a primitive and ArrayList is overrides List in Java*/


RadioButton
List<WebElement> eBoxes=driver.FindElements(By.xpath(//input[@type=’radio’]”));
For(int i=0;i<=eBoxes.size-1;i++) //for(Iterator i=eBoxes;eBoxes.hasnext())
System.out.println(eBoxes.get(i).getattribute(“value”)); // (WebElement)(i . next()). getattribute("value");

Drop Down
1. Select s=new Select(driver.FindElement(By.Xpath("//df/sd")));
s.selectByVisibleText("text here"); //s.selectAll , s.deselectall , s.selectbyIndex
List<WebElement> values=s.getOptions(); //Retrieves all values to list
//LOOPING THROUGH EACH
for(WebElement w:values) // for(Iterator i=values.iterator() ;i.hasnext())
sop(w.getAttribute("value"); // WebElement w=(WebElement)i.next();


2. driver.findElement(By.xpath(“dropdown”)).click();
driver.findElement(By.xpath(“dropdown”)).sendkeys(“abcd”);
driver.findElement(By.xpath(“dropdown”)).click();

Tooltip
System.out.println(driver.findelement(By.Xpath(//body/br”)).getattribute(“title”);

KeyPress:
Driver.findElement(By.Xpath(//body/”)).Sendkeys(“abcd”);
-------------------------------------------------------------------------------------------------------

Handle Windows :
Set<String> winids = driver.getWindowHandles(); \\ Collections =Sets(no duplicates), Map(dictionary),List(ArrayList)
System.out.println(winids.toString()); //prints all window ids
driver.switchTo().window(winids.iterator().next()).close();

Handle Frames
driver.switchTo().frame(id or name);
driver.switchTo().frame(By.Xpath());
List<WebElement> frameList=driver.findElements(By.tagName(“iframe”));

Handle Alert Box
Alert a=driver.switchTo().alert();
System.out.println(a.gettext());
a.accept(); //a.dismiss();

-------------------------------------------------------------------------------------------------------
Different Wait
1. WebDriverWait wait = new WebDriverWait(driver,10);//-------------1
wait.until(ExpectedConditons.elementToBeClickable(By.id/xpath/name("locator"));

2. Thread.Sleep(1000) //----------2

3. driver.manage.timeouts().implicitlywait(10,Timeunits.seconds;)//----------3
3. driver.manage.timeouts().pageloadtimeout(10,Timeunits.seconds;)

Navigate
1. driver.get(“http://www.google.com“ );
2. driver.navigate().to(“http://www.google.com”);
driver.navigate().forward();
driver.navigate().back();
driver.navigate().refresh();
Cookie:
driver.manage().deleteAllCookies();
-------------------------------------------------------------------------------------------------------
FireFox
Download Gecko Driver and Unzip :https://github.com/mozilla/geckodriver/releases

System.setProperty("webdriver.gecko.driver","extracted path\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
Chrome
System.setProperty("webdriver.chrome.driver","Path of Chrome driver");
WebDriver driver=new ChromeDriver();

IE
System.setProperty("webdriver.ie.driver","Your_Path//IEDriverServer.exe");
WebDriver webdriver = new InternetExplorerDriver();
-------------------------------------------------------------------------------------------------------
Execute Java Script
import org.openqa.selenium.JavascriptExecutor;


1. (JavascriptExecutor)driver.executeScript("mouse_hover"); //html -- <div id=*** mouseonhover=mouse_hover >
2. ((JavascriptExecutor) driver).executeScript("alert('hello world');");
3. ((JavascriptExecutor) driver).executeScript("document.getElementById('gbqfbb').click()");

Actions - Double Click , DragDrop and Mouse Related Operation
Actions a =new Actions(driver);

WebElement e1=driver.findElement(By.xpath(""));
WebElement e2=driver.findElement(By.xpath(""));

a.moveToElement(e1).doubleClick().perform(); \\Double click
a.dragAndDrop(e1, e2).perform(); \\Drag Drop
a.moveToElement(e1).moveByOffset(X, Y).click().perform();\\Mouse Move

Robot - To perform mouse related operation
Point coordinates =driver.findElement(By.xpath("//canvas")).getLocation();
System.out.println("Co-ordinates"+coordinates);
Robot robot = new Robot();
robot.mouseMove(coordinates.getX(),coordinates.getY());
robot.mousePress( InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
Screenshot
File f= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(f, new File("c:\\tmp\\screenshot.png"));

DataProvider
@Dataprovider
public Object[][] dp(){Object[][] o=new Object[1][1];
o[0][0]="hi";
o[0][1]=123;
o[1][0]="bye";
o[1]1]=999;
return o;}

@Test(dataprovider="dp") //executed twice with 1st iteration s=hi and i=123 and 2nd iteration s=bye and i=999
public void m(String s,int i){}

Log Error in TestNg report
1)
public class Assert1 {
SoftAssert soft_assert=new SoftAssert();
@Test
public void test1(){
Assert.assertEquals("abc", "ABC");
Reporter.log("Pass");
System.out.println("hi");
}
@Test
public void test2(){
soft_assert.assertEquals("abc", "ABC");
Reporter.log("fail");
System.out.println("bye");
soft_assert.assertAll();
}
}


2)
Class A extends SelenesetestBase
{
String s="";
try{
driver.findelement(By.Xpath()).click();
}catch(Exception.e)
{
s=e.getmessage();
Reporter.log("element not found <br>");
}

if(s.contentequals("")==false)
fail(s);
}

Stringutils.mid (requires apache StringUtils API)
Stringutils.mid(input,start ,number of characters)
EX :Stringutils.mid("ABC",1,2) //output : AB

StringUtils.indexof (requires apache StringUtils API)
StringUtils.indexof(Input,character sequence)
Example : StringUtils.indexof("ABC","B") //output : 2

-------------------------------------------------------------------------------------------------------
Excel (works for both xlsx and xls files .
Also refer "Fast excel" http://catchbug.blogspot.in/2014/10/selenium-fastexcel.html )
import org.apache.poi.ss.usermodel.Workbook; \\poi-3.14.jar
import org.apache.poi.ss.usermodel.WorkbookFactory; \\poi-ooxml-3.14.jar

Workbook wb = WorkbookFactory.create(new FileInputStream("C:\\Users\\DPK\\Desktop\\test.xls"));
Sheet sheet = wb.getSheet("Sheet1");

System.out.println( sheet.getRow(0).getCell(0).getRichStringCellValue() ); // Read Cell
sheet.createRow(1).createCell(1).setCellValue(1212); //---Write into a new cell
sheet.getRow(0).getCell(0).setCellValue("333"); //----Edit existing Cell



System.out.println(sheet.getLastRowNum());
System.out.println(sheet.getRow(0).getLastCellNum());
wb.write(new FileOutputStream("C:\\Users\\DPK\\Desktop\\test.xls"));

Text write File
FileUtils.write(new File("C:\\1.txt"), "hi");

Text ReadFile
String str= FileUtils.readFileToString(new File("C:\\Users\\1.txt")) ;

PropertiesFile
properties p=new properties();
Inputfilestream f=new InputFilestream("C:\\properties_file.properties");
p.load(f);
p.getproperty("excel"); //properties_file.properties :- excel=c:\\1.xls

testng.xml
<suite name="some name">
<test name = "other name">
<parameter name ="var" value="hi"/>
<classes>
<class name = "packagename.class" />
<classes>
</test>
</suite>

build.gradle
apply plugin: 'maven'
apply plugin: 'java'

sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
testCompile'org.testng:testng:6.+'
testCompile 'org.seleniumhq.selenium:selenium-java:2.+'
}

test {
testLogging {
events "passed", "skipped", "failed", "standardError","standardOut" //enable result
}
useTestNG {
suites 'src/testng.xml'
}
}


POM(Page object Model)
class T{
By usn=By.xpath("//*[@name='username']")
By pass=By.xpath("//*[@name='pass']")
By ok=By.xpath("//*[@name='ok']")

@test
public void t1(){
driver.findElement(usn).sendkeys("asas");
driver.findElement(pass).sendkeys("123");
driver.findElement(ok).click();

}
-------------------------------------------------------------------------------------------------------
Misc


1. driver.navigate().refresh();
2. driver.findelement(By.Xpath("Xpath ").getcssvalue("");
3. selenium. Set Speed ("2000")
4. What are desiredcapabilities?ans :enable/disable JS , profile
5. driver.manage().timeunits().pageLoadingtime
6. @Test(priority=4)
7. //*[contains(text(),'b')]
8. FirefoxProfile profile = new FirefoxProfile();
// profile.setPreference("general.useragent.override", "some UA string"); // driver path
profile .addExtension(new File("firebug-1.8.1.xpi")); //addin
// firefoxProfile.setPreference("extensions.firebug.currentVersion", "1.8.1"); // Avoid startup screen
Web Driver driver = new FirefoxDriver(profile);

9. driver.getCapabilities().toString() //Browser name ver


DesiredCapabilities dc = DesiredCapabilities.firefox(); \\Looks like firefox() is a static method in class Desiredcapabilities class
//dc.setCapability(FirefoxDriver.BINARY, new File("path_to_binary").getAbsolutePath());
dc.setJavascriptEnabled(true);
WebDriver driver = new FirefoxDriver(dc);

5 comments:

  1. Hi Deepak,

    Thanks for sharing a great article on Selenium WebDriver Commands .

    I think there are lots of people who struggle while dealing with Selenese -Selenium commands .

    I have also tried my best to write on Selenese which will be helpful to people who are stepping into Selenium Automation.

    I will appreciate if you can take a few minutes to provide your feedback for the same, it would be a great help!!
    Selenium Installation

    Thanks a lot!!

    Regards,
    Sherlin

    ReplyDelete
  2. I simply want to say I’m very new to blogs and actually loved you’re blog site. Almost certainly I’m going to bookmark your blog post . You absolutely come with great well written articles. Thanks a lot for sharing your blog.
    Selenium Training in chennai | java training institutes in chennai

    ReplyDelete
  3. I feel really happy to have seen your webpage and look forward to so many more entertaining times reading here. Thanks once more for all the details.

    selenium training in chennai|

    ReplyDelete
  4. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.

    Data Science Training In Bangalore

    ReplyDelete
  5. I simply wanted to write down a quick word to say thanks to you for those wonderful tips and hints you are showing on this site.
    hadoop training in chennai
    big data training in chennai

    ReplyDelete