How to select a check box in selenium webdriver? - java

Can any one pls help me out
There are many check boxes available with values and I have to choose a particular value in check box. I dont know how to choose a check box value in selenium webdriver
https://www.blueshieldca.com/fap/app/search.html

This one works.. This will click the check box "General Medicine" under "Type" on left menu...
public class SampleUITest extends SeleneseTestBase {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
try {
driver.get("https://www.blueshieldca.com/fap/app/search.html");
driver.findElement(By.id("location"))
.sendKeys("Locans, Fresno, CA");
driver.findElement(By.className("findNow")).click();
Thread.sleep(1000);
driver.findElement(By.className("continueBtn")).click();
Thread.sleep(15000);
driver.findElement(
By.xpath("//ul[#id='doctortypesmodule']/li[2]/input"))
.click();
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}

This works!!
Your actual issue is with wait
#BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.blueshieldca.com/fap/app";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#Test
public void Test01() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 60);
driver.get(baseUrl + "/search.html");
driver.findElement(By.xpath("//input[#name='location']")).clear();
driver.findElement(By.xpath("//input[#name='location']")).sendKeys(
"Los Alamitos, Orange, CA");
driver.findElement(By.xpath("//input[#value='findNow']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//input[#onclick='continueallPlans();']"))
.click();
wait.until(ExpectedConditions.elementToBeClickable(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']")));
List<WebElement> ele = driver
.findElements(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']"));
System.out.println(ele.size());
ele.get(0).click();
}
Prashanth Sams | seleniumworks.com

Related

How to switch between two or mutlple chrome browser windows (Not tabs) using selenium in java?

Here is code that I want to do switching. I do some stuff at user X and then again by calling openbrowser() method I login to user y and do some stuff now want to switch to X user chrome browser again for next actions.
public static void openbrowser() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "/home/chromedriver");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
public static void navigateAppUrl(int row, int column) throws Exception {
driver.get(excel.readData(row , column));
}
public static void LogintoXUser() {
//Do some stuff//
}
public static void LogintoYUser() {
//Do some stuff//
}
public static void main(String args[]){
openbrowser();
navigateAppUrl(1,2);
LogintoXUser()
// new chrome browser instance is created
openbrowser();
navigateAppUrl(1,2);
LogintoYUser()
}
Change method openbrowser() to WebDriver. You can create more instances of WebDriver and arbitrarily use them.
public static WebDriver openbrowser() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "/home/chromedriver");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
return driver;
}
public static void main(String args[]){
WebDriver driver1 = openbrowser();
// do some staff with driver1
WebDriver driver2 = openbrowser();
// do some staff with driver2
// continue with some staff with driver1
driver1....
// continue with some staff with driver2
driver2....
}

Switching between browsers using Linktext in Selenium

This is how you can switch browsers pages using linkText in Selenium as below
public class locatorsPractice {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","/path");
WebDriver driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("https://browser url");
String strMainWindowHandle=driver.getWindowHandle();
System.out.println("Window title"+driver.getTitle());
driver.findElement(By.linkText("Google")).click();
Set <String> strHandles=driver.getWindowHandles();
for (String handle:strHandles) {
driver.switchTo().window(handle);
String strTitle=driver.getTitle();
if(strTitle.equalsIgnoreCase("Google")) {
System.out.println(driver.getTitle());
driver.manage().window().maximize();
Thread.sleep(2000);
driver.close();
}
}
}}

Proper way to pass a webdriver to another class

I want to pass my WebDriver to another class instead of passing it to the individual methods within that class. That would mean passing it to the constructor of the class when I create an instance of it. Here is my code, and my issue further below -
public class StepDefinitions{
public static WebDriver driver = null;
CustomWaits waits;
#Before("#setup")
public void setUp() {
driver = utilities.DriverFactory.createDriver(browserType);
System.out.println("# StepDefinitions.setUp(), driver = " + driver);
waits = new CustomWaits(driver);
}
}
public class CustomWaits {
WebDriver driver;
public CustomWaits(WebDriver driver){
this.driver = driver;
}
public boolean explicitWaitMethod(String id) {
boolean status = false;
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
status = element.isDisplayed();
} catch (NullPointerException e){
e.printStackTrace();
}
return status;
}
}
The error I am getting in is NullPointerException when a method of that class is called within an #Given, #When, etc. This is a scope issue I cannot resolve.
Feature File:
#test
Feature: Test
#setup
Scenario: Navigate to Webpage and Assert Page Title
Given I am on the "google" Website
Then page title is "google"
Here is the step definition:
#Given("^element with id \"([^\"]*)\" is displayed$")
public void element_is_displayed(String link) throws Throwable {
if (waits.explicitWaitMethod(link)) {
// This is where waits becomes null when I put a breakpoint
driver.findElement(By.id(link)).isDisplayed();
} else {
System.out.println("Timed out waiting for element to display");
}
}
I would do something like this.
public class StepDefinitions{
public StepDefinitions() {
driver = utilities.DriverFactory.createDriver(browserType);
System.out.println("# StepDefinitions.setUp(), driver = " + driver);
waits = new CustomWaits(driver);
}
public static WebDriver driver = null;
public static CustomWaits waits;
#Given("^element with id \"([^\"]*)\" is displayed$")
public void element_is_displayed(String link) throws Throwable {
if (waits.explicitWaitMethod(link)) {
// This is where waits becomes null when I put a breakpoint
driver.findElement(By.id(link)).isDisplayed();
} else {
System.out.println("Timed out waiting for element to display");
}
}
}
public class CustomWaits {
private static WebDriver driver;
public CustomWaits(WebDriver driver){
this.driver = driver;
}
public boolean explicitWaitMethod(String id) {
boolean status = false;
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
status = element.isDisplayed();
} catch (NullPointerException e){
e.printStackTrace();
}
return status;
}
}

Chromedriver doesn't opens link a new tab or window , instead the expected link is opened in current tab/window

This is the code i have tried to handle window but the url for opens in the tab of google.
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver =new ChromeDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
Thread.sleep(3000);
for(String windowHandle:driver.getWindowHandles()) {
driver.switchTo().window(windowHandle);
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}
In the iteration over the window handles you are switching to both of them. The last switch returns the focus to the first window and the link is getting opened there.
You should do the switch only to the new window
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
String firstWindowHandle = driver.getWindowHandle();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
Thread.sleep(3000);
for(String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(firstWindowHandle)) {
driver.switchTo().window(windowHandle);
}
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}
Driver is opening in same window, because for loop is switching old handle
Code probably should look like this below
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver =new ChromeDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
String currentHandle = driver.getWindowHandle();
try {
Thread.sleep(3000);
for(String windowHandle:driver.getWindowHandles()) {
if(!currentHandle.equals(windowHandle)){
driver.switchTo().window(windowHandle);
break;
}
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}

How can I change try catch exception to WebDriverWait

I am trying to login and search records based on date selected from a calendar. I have used try catch exception after each step. I need to replace try catch with WebDriverWait. But the problem is that I have fields on the page which are getting identified by id or XPath. So I am not getting a way out how to implement WebDriverWait instead of try catch. Can anyone help me out? Below is my code structure with details.
public class Login {
public static WebDriver driver;
String username = "username";
String password = "password";
String baseurl = "http://mybusiness.com/login.aspx";
public class Details {
#Test(priority = 0)
public void loginpage() {
//WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capabilities.setCapability("chrome.binary","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(password);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement button = driver.findElement(By.id("ButtonClick"));
button.click();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// Selecting a date from date picker
#Test(priority = 1)
public void RecordSearch() {
WebElement calendar = driver.findElement(By.id("CalendarId"));
calendar.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement month = driver.findElement(By.xpath("XPath"));
month.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement day = driver.findElement(By.xpath("XPath"));
day.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement submit = driver.findElement(By.id("Submit"));
submit.click();
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
driver.close();
}
I would have thought you'd be better off adding an implicit wait, e.g. once you've setup your driver object add the following line:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
A simple example would take your code
try
{
Thread.sleep(10000); // 1000 milliseconds is one second.
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
and change it to
String username = "username123";
WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds
WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName")));
usernameField.sendKeys(username);
Once you have defined wait, you can reuse it over and over and it will have the same attributes, e.g. 10 sec wait time.
String password = "abc123";
WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password")));
passwordField.sendKeys(password);
NOTE: I noticed that you were using username.sendKeys(username);. I'm assuming/hoping this isn't actual code since .sendKeys() takes a String and you have username defined as a WebElement. I fixed it in my code and named the two differently.
There is WebDriverWait functionality in selenium, you can set explicit wait. You are using selenium webdriver, then it is far better to use WebDriverWait for waiting purpose to element. follow below code
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Whenever you require wait for element present, call waitForPresent method with expected parameters.
If you explore little, you can find different types of WebDriverWait. One of the most common is WebDriver.wait(timeinmilliseconds).
and for example, others are,
webDriver.waituntil (Expectedconditions)...
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.className("sel"));
String enabled = button.getText();
return enabled.contains(city);
}
});
or for example
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("froexample_username_txtbox")));
PS : define private final WebDriverWait wait;
It may be more useful if you are not sure about implict timewait value.(be being specific about events and results)

Categories

Resources