Selecting dropdown option is NOT working with Selenium - selenium-webdriver

package com.test.utitlity;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.Select;
public class selectDropdown extends globalVariables {
public static void select(String locator, int indexValue) {
Select select= new Select(common.getObject(locator));
//select.selectByValue("selectValue");
System.out.println(indexValue);
select.selectByIndex(indexValue);
}
}
It is clicking the dropdown but not selecting the option.. Dropdown is empty.. How to resolve this?? But When I run the debug mode, it is working as expected. Added wait condition but getting IllegalStateException..

Can you try the below one and let me know what is the Result.
WebDriverWait Test_Wait = new WebDriverWait(driver, 10);
WebElement Drop_down = Test_Wait.until(ExpectedConditions.elementToBeClickable(common.getObject(locator)));
List<WebElement> lst2 = Drop_down.findElements(By.xpath(".//option[contains(text(),'Your_Option_Text')]"));
for (WebElement option : lst2)
{
if (!option.isSelected())
{
option.click();
}
}

Related

How to define actions in page object modeling

I am newbee to selenium. I was trying to access menu->sub-menu in PageObject Modeling.
My requirement is to click on Menu item and sub-menu item which appears dynamically.
I was going through StackOverflow and in one of the resolutions it was mentioned to write Actions as
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
However i can't pass driver in constructor. if I pass constructor i am getting problem while running this script. The error is below
FAILED: checkLinks java.lang.Error: Unresolved compilation problem:
The method HomePageLinksClick(WebDriver) in the type HomePageLinksTest is not applicable for the arguments ()
If I include WebDriver driver in constructor as a parameter, my page class is not accepting that as parameter. Can anyone help?
Page Class
package au.com.sreetechconsulting.Pages;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import au.com.sreetechconsulting.TestCases.HomePageLinksTest;
public class HomePage {
public WebDriver driver;
#BeforeTest
public void openBrowser() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.sreetechconsulting.com.au/");
}
#Test
public void checkLinks() {
HomePageLinksTest linkClick = new HomePageLinksTest(driver);
linkClick.HomePageLinksClick();
}
}
Test Page Class
package au.com.sreetechconsulting.TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HomePageLinksTest {
#FindBy(css="#header > div.container > div > div.col-md-9.main-nav > nav > ul > li:nth-child(2) > a")
private WebElement currentOpenings;
#FindBy(css="#header > div.container > div > div.col-md-9.main-nav > nav > ul > li:nth-child(2) > ul > li:nth-child(1) > a")
private WebElement ausJobsSubmenu;
public HomePageLinksTest (WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void HomePageLinksClick() {
//currentOpenings.click();
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
}
}
You can keep the driver as a class member from the constructor
public class HomePageLinksTest {
private WebDriver driver;
public HomePageLinksTest (WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void HomePageLinksClick() {
//currentOpenings.click();
Actions actions = new Actions(driver);
actions.moveToElement(currentOpenings).build().perform();
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(ausJobsSubmenu));
}
}
And in the test use it like this
#Test
public void checkLinks() {
HomePageLinksTest linkClick = new HomePageLinksTest(driver);
linkClick.HomePageLinksClick();
}

How to select specific flight record on flight selection page, using Selenium webdriver

I am able to navigate to Flight Reservation page on website - http://www.spicejet.com/. Code is given below:
Code:
package Flight_Reservation;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class NewFlight_OneWay {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\Selenium_Practice\\EXEs\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='ctl00_mainContent_rbtnl_Trip_1']")).click();
//Select origin
driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).sendKeys("DEL");
driver.findElement(By.linkText("Delhi (DEL)")).click();
//Select destination
driver.findElement(By.id("ctl00_mainContent_ddl_destinationStation1_CTXT")).sendKeys("BOM");
driver.findElement(By.linkText("Mumbai (BOM)")).click();
WebElement DateWidget = driver.findElement(By.id("ui-datepicker-div"));
List<WebElement> columns = DateWidget.findElements(By.tagName("td"));
for (WebElement cell: columns)
{
if (cell.getText().equals("24"))
{
cell.findElement(By.linkText("24")).click();
break;
}
}
Select AdultDropdown = new Select(driver.findElement(By.id("ctl00_mainContent_ddl_Adult")));
AdultDropdown.selectByValue("2");
Select ChildrenDropdown = new Select(driver.findElement(By.id("ctl00_mainContent_ddl_Child")));
ChildrenDropdown.selectByValue("1");
Select InfantDropdown = new Select(driver.findElement(By.id("ctl00_mainContent_ddl_Infant")));
InfantDropdown.selectByValue("1");
Select CurrencyDropdown = new Select(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")));
CurrencyDropdown.selectByValue("INR");
driver.findElement(By.id("ctl00_mainContent_btn_FindFlights")).click();
}
}
Question:
On flight selection page, I want to select flight record radio button with flight name 'SG 161'. Please let me know how can I achieve that?
Use following code to click on required radio-button:
driver.findElement(By.xpath('//input[#type="radio"][contains(#value, "SG~ 161")]')).click();

Webpage stops to respond after selecting a date using webdriver click updated

we have a webpage with 2 date calender one is a current date the other is referencedate which autoupdates itself to display a day less than the current date.
issue-After selecting a date from a calender using webdriver click the other
calender which had to update the date automatically, does not update anymore.
The same actions if performed manually works.
Has anybody faced a similiar issue, this has become a blocker since with the autoupdate not working the entire application workflow fails.
removed sensitive data
package pages;
import java.util.Calendar;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.SendKeysAction;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.webdriven.SeleniumMutator;
import com.thoughtworks.selenium.webdriven.commands.SeleniumSelect;
import utils.Waitutils;
public class CalenderPage {
WebDriver driver;
static WebDriverWait wait;
public CalenderPage (WebDriver driver){
this.driver = driver;
}
public void cobDatepick(String date){
int count=0;
WebElement cob =driver.findElement(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/span"));
cob.click();
WebElement mLink = driver.findElement(By.xpath("//button[contains(#id,'datepicker')]"));
String date_dd_MM_yyyy[] = (date.split(" ")[0]).split("/");
int yearDiff = Calendar.getInstance().get(Calendar.YEAR) - Integer.parseInt(date_dd_MM_yyyy[2]);
mLink.click();
WebElement pLink = driver.findElement(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/thead/tr[1]/th[1]/button/i"));
if(yearDiff>0){
for(int i=0;i<yearDiff;i++){
pLink.click();
}
}
List<WebElement> months1 = driver.findElements(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/tbody/tr/td"));
months1.get(Integer.parseInt(date_dd_MM_yyyy[1])-1).click();
List<WebElement> dates = driver.findElements(By.xpath("//*[#id='mainview']/div/div[2]/div[1]/div/options-panel-directive/div[2]/div[1]/div/div[1]/date-picker/div[2]/div/ul/li[1]/div/table/tbody/tr//td"));
int total_nodes = dates.size();
for(int i=0; i<total_nodes; i++)
{
String dat = dates.get(i).getText();
if(dat.equals(date_dd_MM_yyyy[0])&& count>0)
{
dates.get(i).click();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.document.getElementById('date-picker-to').setAttribute('value', '30/06/2016');");
}
if(dat.equals(date_dd_MM_yyyy[0]))
{
count++;
}
}
}
}
The above class is called in the testscript
#BeforeTest
public void setup() throws Exception{
driver = new AppDriver("ie").getDriver();
driver.get("https://xyz");
driver.manage().window().maximize();
onCalenderPage = new CalenderPage (driver);
Waitutils.waitforCompletion(9000L);
}
#Test
public void test(){
onCalenderPage.cobDatepick("30/06/2016");
}

autosuggest textbox using webdriver java

I'm i\using webdriver version2.41 and browser is Firefox 28. I'm trying to find a listcount of elements present in the drop down list of a auto suggest textbox.Ex: in Google.co.in page i'm writing Banga to get the suggestions for Bangalore. Once i get the suggestion list then i want to dispay all the Auto suggested text on the screen. I have written the code, but don't know why its not working. I'm anew bie to selenium webdriver. Please help me. Here is my code :
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class test {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
List<WebElement> lstobj = driver.findElements(By.xpath("//div[#class='gsq_a']/table/tbody/tr/td/span/b"));
System.out.println(lstobj.size());
for (int i = 0; i<lstobj.size();i++)
{
String p= lstobj.get(i).getText();
System.out.println(p);
}
}
}
I hope this helps u..
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class google{
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
WebElement parent=driver.findElement(By.className("gssb_e"));
List<WebElement> child = parent.findElements(By.tagName("div"));
int size=child.size();
System.out.println(size);
for (int i =1; i<=size;i++)
{
String p= driver.findElement(By.xpath("//*[#id='gsr']/table/tbody/tr[1]/td[2]/table/tbody/tr["+i+"]/td/div/table/tbody/tr/td[1]")).getText();
System.out.println(p);
driver.close();
}
}
}
Edited the xpath used by you and the way you retrieved text :
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class test {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.co.in");
driver.findElement(By.id("gbqfq")).sendKeys("Banga");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
List<WebElement> lstobj = driver.findElements(By.xpath("//table[#class='gssb_m']/tbody/tr"));
System.out.println(lstobj.size());
for (int i = 0; i<lstobj.size();i++)
{
String p= lstobj.get(i).findElement(By.xpath("//span")).getText();
System.out.println(p);
}
}
driver.get("https://www.google.co.in/");
driver.findElement(By.xpath("//input[#class='gLFyf gsfi']")).sendKeys("Banga");
//This will also work USE descendant to get all child element
List<WebElement> printlist = driver.findElements(By.xpath("//ul[#role='listbox']//li/descendant::div[#class='sbl1']"));
System.out.println(printlist.size());
for ( WebElement list: printlist) {
//if you want to specify condition here you can
System.out.println(list.getText());
}

Selenium Web driver--Failure Screenshot is not captured in TestNG report

With below mentioned code,if the test case is pass-screenshot captured successfully and displayed in report.But when the test is failed--screenshot is not displayed.Even screenshot hyperlink is not displayed in report.Anybody can sort out the mistake in code?
package listeners;
import java.io.File;
import java.io.IOException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
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.firefox.FirefoxDriver;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import org.testng.ITestResult;
import org.testng.Reporter;
import org.testng.TestListenerAdapter;
import java.util.logging.Logger;
#Listeners
public class CountryChoserLayer extends TestListenerAdapter {
#Test(priority=1)
public void choseCountry() throws Exception{
driver.findElement(By.id("intselect")).sendKeys("India");
driver.findElement(By.xpath(".//*[#id='countryChooser']/a/img")).click();
//window.onbeforeunload = null;
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
FileUtils.copyFile(scrnsht, new File(NewFileNamePath));
System.out.println(NewFileNamePath);
Reporter.log("Passed Screenshot");
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case-Success");
System.out.println("---------------------------------------");
}
public String baseurl="http://www.sears.com/shc/s/CountryChooserView?storeId=10153&catalogId=12605";
public WebDriver driver;
public int Count = 0;
#Test(priority=0)
public void openBrowser() {
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.get(baseurl);
}
#Test(priority=2)
public void closeBrowser() {
driver.quit();
}
#Override
public void onTestFailure(ITestResult result){
Reporter.log("Fail");
System.out.println("BBB");
//Reporter.setCurrentTestResult(result);
Date date=new Date();
Format formatter = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss");
File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//File scrFile = ((TakesScreenshot) WebDriver.globalDriverInstance).getScreenshotAs(OutputType.FILE);
String NewFileNamePath=("C://Documents and Settings//vlakshm//workspace//MyTNG//test-output//Screenshots"+"//SearsINTL_"+ formatter.format(date)+".png");
//System.out.println("AAA" + NewFileNamePath);
try {
//System.out.println("CCC");
FileUtils.copyFile(scrnsht,new File(NewFileNamePath));
System.out.println(NewFileNamePath);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("DDD");
e.printStackTrace();
}
Reporter.log("Failed Screenshot");
Reporter.setCurrentTestResult(null);
System.out.println("---------------------------------------");
System.out.println("Country choser layer test case Failed");
System.out.println("---------------------------------------");
}
#Override
public void onTestSkipped(ITestResult result) {
// will be called after test will be skipped
Reporter.log("Skip");
}
#Override
public void onTestSuccess(ITestResult result) {
// will be called after test will pass
Reporter.log("Pass");
}
}
Your onTestFailure method is not being called because you didn't specify listener for your test class. You are missing a value in #Listeners annotation. It should be something like
#Listeners({CountryChoserLayer.class})
You can find more ways of specifying a listener in official TestNg's documentation.
Another problem you are likely to encounter would be NullPointerException while trying to take screenshot in onTestFailure method. The easiest workaround for that would be changing the declaration of driver field to static. I run the code with those fixes and I got the report with screenshot.
I must add that in my opinion putting both test and listener methods into one class is not a good practice.

Resources