How can we select the dropdown value in selenium webdriver using Testng?
Selecting dropdown values in selenium webdriver is not a part of TestNG, it's part of selenium+java code.
Use below code for reference ::
public class temp {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.shoppersstop.com/shoes/kids-shoes/all/brand/kittens.html");
WebElement selectElement = driver.findElement(By
.xpath("//select[#class='subCatThree' and #name='category']"));
Select select = new Select(selectElement);
List<WebElement> options = select.getOptions();
for (WebElement option : options) {
System.out.println(option.getText());
if (option.getText().equals("Girls ( 3 Years & Above)")) {
option.click();
break;
}
}
}
If you want to select by value
Select select = new Select(driver.findelement(By.xpath("write the xpath of dropdown")));
select.selectByValue("write value here");
If you want to select by Text
Select select = new Select(driver.findelement(By.xpath("write the xpath of dropdown")));
select.selectByVisibleText("write text here");
How do we convert this code to use Selenium WebDriver
If Browser("UOB").Page("pgeSetCustomLimits").Exist(intSyncTime*1) Then
Set oDesc=Description.Create
oDesc("micclass").Value = "WebElement"
oDesc("html id").Value = "limitsInput_CI_form_label_div"
Set ObjEle =
Browser("UOB").Page("pgeSetCustomLimits").ChildObjects(oDesc)
For i=0 to ObjEle.count-1
strWebEleText = ObjEle(i).getRoProperty("innertext")
'print strWebEleText
If Instr(strWebEleText,strPaymentType) Then
intRow = i
Exit For
End If
Next
End If
Related
I am a complete beginner in Selenium and I am not able to automate the Selenium code below. I have tried numerous methods but I am still getting issues with automating the run from getting the data from excel. I have even tried using the TestNG method as well but no luck I am stuck on this part not. Can someone help on how to automate this code without changing the row numbers in this step for (int i= 1; i<=noOfRows ; i++).
The code used:
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("driver location");
WebDriver driver = new FirefoxDriver();
driver.get("link");
FileInputStream file = new FileInputStream("xcel file location");
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet= workbook.getSheet("SO Reg");
int noOfRows = sheet.getLastRowNum(); // returns the row count
System.out.println("No. of Records in the Excel Sheet:" + noOfRows);
int cols=sheet.getRow(1).getLastCellNum();
System.out.println("No. of Records in the Excel Sheet:" + cols);
for (int i= 1; i<=6; i++)
{
String SO_Name = row.getCell(0).getStringCellValue();
String Contact_Person = row.getCell(1).getStringCellValue();
String Address_1 = row.getCell(2).getStringCellValue();
String Address_2 = row.getCell(3).getStringCellValue();
String City = row.getCell(4).getStringCellValue();
String State = row.getCell(5).getStringCellValue();
String ZipCode = row.getCell(6).getStringCellValue();
String Phone_Number = row.getCell(8).getStringCellValue();
String Username = row.getCell(9).getStringCellValue();
String Email = row.getCell(10).getStringCellValue();
String Re_Type_Email = row.getCell(11).getStringCellValue();
//Registration Process
driver.findElement(By.cssSelector("p.text-white:nth-child(4) > a:nth-child(1)")).click(); //create an account
Thread.sleep(5000);
//Enter Data information
driver.findElement(By.id("SOName")).sendKeys(SO_Name);
driver.findElement(By.xpath("//*[#id=\"ContactPerson\"]")).sendKeys(Contact_Person);
driver.findElement(By.xpath("//*[#id=\"AddressLine1\"]")).sendKeys(Address_1);
driver.findElement(By.xpath("//*[#id=\"AddressLine2\"]")).sendKeys(Address_2);
driver.findElement(By.id("City")).sendKeys(City);
driver.findElement(By.id("State")).sendKeys(State);
driver.findElement(By.id("ZipCode")).sendKeys(ZipCode);
driver.findElement(By.id("Phone")).sendKeys(Phone_Number);
driver.findElement(By.xpath("//*[#id=\"UserName\"]")).sendKeys(Username);
driver.findElement(By.xpath("//*[#id=\"Email\"]")).sendKeys(Email);
driver.findElement(By.xpath("//*[#id=\"RandText\"]")).sendKeys(Re_Type_Email);
driver.findElement(By.id("ConfirmBox")).click();
driver.findElement(By.xpath("/html/body/app-root/app-soregistration/div[2]/div/div/div/div/form[2]/div/div[12]/div/button[1]")).click();
driver.findElement(By.cssSelector(".btn-green-text-black")).click(); //finish button
driver.findElement(By.cssSelector("p.text-white:nth-child(4) > a:nth-child(1)")).click(); //create an account
Thread.sleep(5000);
}
}
}
}
java
selenium
automation
katalon-studio
I have a webtable for which I have to fetch the last row . The problem is that the webtable is dynamic so I don't know the row number.I have tried below code but the row number is static there which will fail.
List<WebElement> rows=driver.findElements(By.xpath("//table[1]/tbody/tr[5]"));
to get last element use (locator)[last()] method, like:
WebElement lastRow = driver.findElement(By.xpath("(//table[1]/tbody/tr)[last()]"));
which is shorted variant of:
(locator)[position() = last()]
public class LastRowFetching {
public static void main(String[] args) throws ParseException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
driver= new ChromeDriver();
driver.get("http://money.rediff.com/gainers/bsc/dailygroupa?");
//No.of rows
List rows = driver.findElements(By.xpath(".//*[#id='leftcontainer']/table/tbody/tr/td[1]"));
System.out.println("No of rows are : " + rows.size());
int lastRow = rows.size();
WebElement lastRowFetch =driver.findElement(By.xpath(".//*[#id='leftcontainer']/table/tbody/tr/td["+lastRowcount+"])"));
driver.close();
}
}
int lastRowcount=driver.findElement(By.xpath("//table[1]/tbody/")).findElements(By.tagName("tr")).size();
WebElement Lastrow =driver.findElement(By.xpath("//table[1]/tbody/tr["+lastRowcount+"]"));
In first Line we get the Last Row count from the table.
On second line we get the Last row Element from the table.
I'm trying to show all the selected options from a multi select drop down list. But not getting the proper way to do this. Please help me on this.
Here is the html code for the drop down:
<select multiple id="fruits">
<option value="banana">Banana</option>
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="grape">Grape</option>
</select>
Here is the code i'm trying with:
public void dropDownOperations()
{
driver.get("http://output.jsbin.com/osebed/2");
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
String currentvalue = DDLIST.getFirstSelectedOption().getText();
System.out.println(currentvalue);
DDLIST.selectByIndex(1);
String currentvalue1 = DDLIST.getFirstSelectedOption().getText();
System.out.println(currentvalue1);
}
I also tried with this code:
Here i'm getting this output:
[[[[[ChromeDriver: chrome on XP (69aee19e9922ca218ff47c0ccdf1bbbc)] ->
id: fruits]] -> tag name: option], [[[[ChromeDriver: chrome on XP
(69aee19e9922ca218ff47c0ccdf1bbbc)] -> id: fruits]] -> tag name:
option]]
public void dropDownOperations1()
{
driver.get("http://output.jsbin.com/osebed/2");
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
DDLIST.selectByIndex(1);
List<WebElement> currentvalue1 = DDLIST.getAllSelectedOptions();
System.out.println(currentvalue1);
}
Your second approach should work fine with a minor fix. getAllSelectedOptions() will return a List of selected options as WebElement. You need to iterate over the list to get the text from WebElement.
List<WebElement> selectedOptions = DDLIST.getAllSelectedOptions();
for (WebElement option : selectedOptions){
System.out.println(option.getText());
}
Try This:
List<WebElement> allSelected = select.getAllSelectedOptions();
Iterator itr = allSelected.iterator();
while(itr.hasNext()){
WebElement item = (WebElement) itr.next();
System.out.println(item.getText());
}
Try this below code, It will select one by one options from dropdown.
Select DDLIST = new Select(driver.findElement(By.id("fruits")));
DDLIST.selectByIndex(0);
DDLIST.selectByIndex(1);
List<WebElement> selectedOptions = DDLIST.getAllSelectedOptions();
for(int i=0; i<selectedOptions.size(); i++)
{
System.out.println(DDLIST.getOptions().get(i).getText());
}
Try This:
System.out.println(DDLIST.selectByIndex(0).getText());
System.out.println(DDLIST.selectByIndex(1).getText());
And so on. Instead of using a variable and trying it.
Try this:
Select DDLIST = new Select (driver.findElement(By.id("fruits")));
for(int i=0; i<DDLIST.getOptions().size(); i++)
System.out.println(DDLIST.getOptions().get(i).getText());
I'm trying to choose elements in "Category" one-by-one on this page with:
WebElement category = new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("tr[__gwt_row='" + rowIndex + "'] > td > div")))
.get(3);
category.click();
category.findElement(By.tagName("select")).sendKeys("Businesses");
category.click();
category.findElement(By.tagName("select")).sendKeys("Contacts");
Throwing this : "stale element reference: element is not attached to the page document"
Maybe exists some another way to do it?
UPD:
It works if i do this:
WebElement categoryBusinesses = new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("tr[__gwt_row='" + rowIndex + "'] > td > div")))
.get(3);
categoryBusinesses.findElement(By.tagName("select")).sendKeys("Businesses");
WebElement categoryContacts = new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.cssSelector("tr[__gwt_row='" + rowIndex + "'] > td > div")))
.get(3);
categoryContacts.findElement(By.tagName("select")).sendKeys("Contacts");
But is it a right way?
UPD2:
I also tried this:
WebElement element = categoryBusinesses.findElement(By.tagName("select"));
Select category = new Select(element);
category.selectByIndex(0);
category.selectByIndex(1);
But it not works.
This was really annoying... the problem is that every time you change the value of the SELECT, the page is recreating the element thus causing your reference to become stale. You have to refetch it basically every time you interact with it.
I generally make functions out of things like this so that they are reusable.
public static void GetCategoriesFromRow(int row)
{
By locator = By.cssSelector("table[__gwtcellbasedwidgetimpldispatchingfocus] tr[__gwt_row='" + row + "'] select");
for (int i = 0; i < new Select(driver.findElement(locator)).getOptions().size(); i++)
{
new Select(driver.findElement(locator)).selectByIndex(i);
System.out.println(new Select(driver.findElement(locator)).getFirstSelectedOption().getText());
}
}
You call it like
driver.get("http://samples.gwtproject.org/samples/Showcase/Showcase.html#!CwCellTable");
new WebDriverWait(driver, 10)
.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("table[__gwtcellbasedwidgetimpldispatchingfocus]")));
GetCategoriesFromRow(0);
Try this:
WebElement element = categoryBusinesses.findElement(By.xpath("//*[#id="gwt-debug-contentPanel"]/div[2]/div/div[2]/div/div[3]/div/div/div/table/tbody/tr[1]/td/table/tbody[1]/tr[1]/td[4]/div/select"));
Select category = new Select(element);
category.selectByIndex(0);
category.selectByIndex(1);
This should work.
This is the website I am testing https://www.sydneyairport.com.au/go/car-parking.aspx , I am almost done , but have been stuck in a single issue .
I have selected "date and time" from entry-date section but cannot select "date and time" from exit-date section.
I am clueless why I am not able to it since its the same structure for both and I was able to do it for entry-date ,I don't understand what changes for exit date section . I am new to selenium and will appreciate if anybody helps me out .
This is what I have written to select date and time in entry date section .
public void selectDate(WebDriver driver, String fromDate, String toDate) {
// selects from date
WebElement dateButton = driver.findElement(By.id("period_picker_0"));
dateButton.click();
WebElement datepicker = driver.findElement(By.xpath("//div[#class='period_picker_days']/table/tbody/tr/td[1]"));
selectDate(datepicker, fromDate);
WebElement timeBox = driver.findElement(By.xpath("//div[#class='period_picker_work']/div[2]/input"));
timeBox.sendKeys("");
WebElement time = driver
.findElement(By.xpath(".//*[#id='timepicker_box_start']/div/div[2]/div/div[1]/div[13]"));
time.click();
// Selects to date
WebElement dateButton2 = driver.findElement(By.id("period_picker_1"));
dateButton2.click();
// dateButton.click();
WebElement datepicker2 = driver
.findElement(By.xpath("//div[#class='period_picker_days']/table/tbody/tr/td[2]"));
selectDate(datepicker2, toDate);
WebElement timeBoxEnd = driver.findElement(By.xpath("//div[#class='period_picker_work']/div[2]/input"));
timeBoxEnd.sendKeys("");
WebElement timeEnd = driver
.findElement(By.xpath(".//*[#id='timepicker_box_end']/div/div[2]/div/div[1]/div[13]"));
timeEnd.click();
}
public int selectDate(WebElement datepicker, String date) {
int ele = 0;
List<WebElement> rows_table = datepicker.findElements(By.tagName("tr"));
int rows_count = rows_table.size();
for (int row = 0; row < rows_count; row++) {
// To locate columns(cells) of that specific row.
List<WebElement> Columns_row = rows_table.get(row).findElements(By.tagName("td"));
// To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
// Loop will execute till the last cell of that specific row.
for (int column = 0; column < columns_count; column++) {
// To retrieve text from that specific cell.
if (Columns_row.get(column).getText().equals(date)) {
ele = column;
Columns_row.get(column).click();
}
}
}
return ele;
}
I did lot of work for this code, You are using tr and td. I would suggest there is no need of it.
See the code I'm using, i am able to select both date easily. Hope this help you..
driver.get("https://www.sydneyairport.com.au/go/car-parking.aspx");
driver.manage().window().maximize();
driver.findElement(By.xpath(".//*[#id='period_picker_0']")).click();
Actions a = new Actions(driver);
WebDriverWait wait = new WebDriverWait(driver,20);
WebElement entrydate= driver.findElement(By.xpath(".//*[#id='body']/div[1]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[5]/td[5]"));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='body']/div[1]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[5]/td[5]")));
a.moveToElement(entrydate).build().perform();
Thread.sleep(5000L);
entrydate.click();
WebElement entrytime= driver.findElement(By.xpath(".//*[#id='timepicker_box_start']/div/div[2]/div/div[1]/div[15]"));
a.moveToElement(entrytime).build().perform();
Thread.sleep(5000L);
entrytime.click();
WebElement exitdate= driver.findElement(By.xpath(".//*[#id='body']/div[2]/div[2]/div[1]/table/tbody/tr/td[1]/table/tbody/tr[6]/td[5]"));
a.moveToElement(exitdate).build().perform();
Thread.sleep(5000L);
exitdate.click();
WebElement exittime= driver.findElement(By.xpath(".//*[#id='timepicker_box_end']/div/div[2]/div/div[1]/div[15]"));
a.moveToElement(exittime).build().perform();
Thread.sleep(5000L);
exittime.click();
Please do reply, how you find this and reply back to me for further query.
Happy Learning. :-)