Selenium can be downloaded from here
Getting started guide
Following program will demonstrate some of the basic functionalists of the selenium.
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class SeleniumBasics {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//get configured webdriver
WebDriver driver=getWebdriver();
//goto google.lk
driver.get("http://www.google.lk");
WebElement searchBox=driver.findElement(By.xpath("//input[@type='text' and @name='q']"));
//enter some text in the search textbox
searchBox.sendKeys("Namo Buddhaya!!!");
//cick on search button
WebElement searchButton=driver.findElement(By.xpath("//button[@aria-label='Google Search' and @name='btnG']"));
searchButton.click();
//waiting until results div is loading successfully or 5sec is over
long endTime=System.currentTimeMillis()+5000;
while(System.currentTimeMillis()<endTime){
WebElement resultsDiv=driver.findElement(By.xpath("//div[@id='ires']"));
if(resultsDiv.isDisplayed()){
break;
}
}
//list down the search results
List<WebElement> searchResults=driver.findElements(By.xpath("//a[@class='l']"));
for(WebElement w : searchResults){
System.out.println(w.getText());
}
//saving a screenshot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
System.out.println("-==DONE==-");
}
//creates the default driver
public static WebDriver getWebdriver() {
WebDriver driver = null;
try {
File firebug = new File("C:\\FFPlugins\\firebug-1.7.3.xpi");
File xpathChecker = new File("C:\\FFPlugins\\xpath_checker-0.4.4-fx.xpi");
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(true);
profile.addExtension(firebug); //installing pligins
profile.addExtension(xpathChecker);
profile.setPreference("extensions.firebug.currentVersion", "1.7.3");
profile.setPreference("extensions.xpath_checker.currentVersion", "0.4.4");
driver=new FirefoxDriver(profile);
} catch(IOException e) {
e.printStackTrace();
}
return driver;
}
}

0 comments:
Post a Comment