Selenium Apply button not working on combo box? - java

I have problem with apply button. I have combo box filter and everything is fine, it is switching between squares.But when it suppose to do apply, somehow it just continue like it is not selected anything and test finishes successfully, but there is no filtering that I need.
Can someone check my code and part with inspector bug. Maybe I am missing something?
My Java code:
if (type.equals("")) {
elementList = driver.findElements(By.xpath("//div[#id='" + id + "_menu']//a[#class='FIText']"));
if (elementList.size() > 0) {
if (driver.findElements(By.xpath("//div[#id='" + id + "_menu']//div[#class='CFApplyButtonContainer']//button[#class='tab-button']//span[#class='label'][text()='Apply']/..")).size() > 0) {
type = "multi_checkbox_with_apply";
}else {
type = "multi_checkbox_without_apply";
}
}
}
Inspector bug:
<div class="CFApplyButtonConatiner" style="height: 21px;">
<button class="tab-button tab-widget disabled" type="button" style="max-width: 56px" disabled="">
<span class="icon"></span>
<span class="label">Cancel</span>
</button>
<button class="tab-button tab-widget focus disabled" type="button" style="max-width: 56px" disabled="">
<span class="icon"></span>
<span class="label">Apply</span>
</button>
Can someone check this please?
I don't have idea why it is not working? Maybe someone has idea how to test it.
BR,
Marija

Just to be clear, this solution will look for element which is displayed and it will click on it!!
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.CFApplyButtonConatiner"))));
List<WebElement> elementsList = driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button");
for(WebElement ele: elementsList) {
if(ele.isDisplayed()) {
ele.click();
}
}

I have used like Ranijth's suggestion:
if (type.equals("")) {
elementList = driver.findElements(By.xpath("//div[#id='" + id + "_menu']//a[#class='FIText']"));
if (elementList.size() > 0) {
//if (driver.findElements(By.xpath("//div[#id='" + id + "_menu']//div[#class='CFApplyButtonContainer']//button[#class='tab-button']//span[#class='label'][text()='Apply']/..")).size() > 0) {
if (driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button"))!=null) {
//if (driver.findElements(By.cssSelector("div.CFApplyButtonConatiner > button")).size() > 0) {
type = "multi_checkbox_with_apply";
}
else {
type = "multi_checkbox_without_apply";
}
}
}
And now it is working fine, but now I need to test it to check output. If someone have better solution, let me know.

Related

Unable to Click button in Selenium

Im having difficulties in locating an element which is a finish button within a page. I have used driver.findElementById("finish").click (); and it does not work.
Below are different examples I used but with no success:
for (WebElement Element : driver.findElement(By.id("finish")).findElements(By.tagName("a"))) {
if (Element.getAttribute ("class").contains("criteria-filter")) { Element.click();
break;
}
----------------------------------------------------------------
WebElement click1 = new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#id=\"finish\"]")));
((JavascriptExecutor) driver).executeScript("arguments[0].click();",click1);
----------------------------------------------------------------
if(!driver.findElementById("finish").isEnabled())
{
driver.findElementById("finish").click();
}else{
System.out.println("False");
}
Element:
<a id="finish" access="" allof="PA.DEPLOYMENT_CONFIG" class="btn criteria-filter btn-success" href="" ng-click="verifyAllFields(sftpForm) && sftpForm.$valid && create()">Finish
</a>
Class selector is not the best idea as it will fail if there is more elements with the same class.
The best way is to open dev-tools, click ctrl + f, then try to cath your element by xpath like this:
//a[text()='Finish']
When you "cath" this browser will move to that element.

Unable to check state of elements

I am trying to automate for my first time a complete flow for a e-comm app. After Add to cart button is clicked, a quantity spinner is displayed instead of that button, with "+" and "-" buttons. I am trying to determine if the button was clicked. If so, click on "-" button and then click again on Add to Cart button for that element and move to next button and so on. This is what I have done so for, but without any luck:
private static void addProductsToCart()
{
List<WebElement> buttons = driver.findElements(By.className("actions__addToCart"));
WebElement action = driver.findElement(By.xpath("//*[#id=\"content\"]/div/section/ul/div/div/li/div/div/div/div/div/button[1]"));
for(int i = 0; i <= buttons.size(); i++)
{
if(action != null && action.isDisplayed())
{
action.click();
}
buttons.get(i).click();
if(i == 4)
{
break;
}
}
}
Any help would be much appreciated.
<div class="quantitySpinner alignmentContainer__element" data-bind="visible: size().quantity() > 0" style="">
<button class="decrease" data-bind="click: decrementQuantity, attr: {'aria-label': ogs.gsa.resources.Accessibility_DecreaseQuantity.formatWith({productBrand: model.Brand, productName: model.Name})}" aria-label="Subtract One Birds Eye Steamfresh Chef's Favorites Rotini & Vegetables"></button>
<label data-bind="text: size().quantity, attr:{'aria-live':'polite', 'aria-atomic':'true'} " aria-live="polite" aria-atomic="true">1</label>
<button class="increase" data-bind="click: incrementQuantity, attr: {'aria-label': ogs.gsa.resources.Accessibility_IncreaseQuantity.formatWith({productBrand: model.Brand, productName: model.Name})}" aria-label="Add One Birds Eye Steamfresh Chef's Favorites Rotini & Vegetables"></button>
</div>
For clicking on decrease button, you can try this code :
WebDriverWait wait = new WebDriverWait(driver , 20);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.decrease"))).click();
As you have mentioned, that you want to click on click again on Add to Cart button
for that :
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpath of add to cart button
or any other locator as per your convenience ")))

navigate between pages with selenium - Java

I walk a list of links , I click on them one by one , I go to the page the link and realize the actions that need to perform and then return to the list to click on the next link, it is working perfectly.
What I need now is to come to the end of the links , where the loop ends , the selenium click the forward button to go to the next page and be done again the link count of this page and start the cycle again.
I can not make the selenium click the move because it says that the click(); command You can not be using in a webelento .
The method click () is undefined for the type List < WebElement >
This is the HTML structure:
<div id="results-pagination">
<h2 id="pagination-heading">Pagination</h2>
<ul class="pagination">
<li class="prev">
<a class="page-link" href="url" title="back" data-li-page="1">< back</a>
</li>
<li class="link">
<a class="page-link" href="url" title="page 2" data-li-page="2">2</a>
</li>
<li class="next">
<a class="page-link" href="next" title="next" data-li-page="next"></a>
</li>
</ul>
</div>
selenium code:
List<org.openqa.selenium.WebElement> numberpages= driver.findElements(By.className("page-link"));
System.out.println("numberpages : " + numerospaginas.size());
List<org.openqa.selenium.WebElement> links= driver.findElements(By.linkText("to connect"));
System.out.println("Count to connect : " + links.size());
Thread.sleep(2000);
for(int i=0;i<5;i++){
links= driver.findElements(By.linkText("to connect"));
links.get(i).click();
Thread.sleep(2000);
boolean convite = driver.getPageSource().contains("iweReconnectSubmit");
if(invite == true){
Thread.sleep(2000);
boolean error = driver.getPageSource().contains("message:");
do{
//action
By tipoPlano = By.cssSelector("[name='reason'][value='IF'][type='radio']");
driver.findElement(tipoPlano).click();
}while(error == true);
//submit
driver.findElement(By.name("iweReconnectSubmit")).click();
Thread.sleep(2000);
WebDriverWait confirmacaoadicao = new WebDriverWait(driver, 10);
confirmacaoadicao.until(ExpectedConditions.textToBePresentInElement(By.id("control_gen_3"), "invite for: "));
String pessoa = driver.findElement(By.xpath("//div[#id='control_gen_3']//a")).getText();
System.out.println(pessoa + " add" );
driver.navigate().to(list_of_links);
WebDriverWait retorno = new WebDriverWait(driver, 10);
retorno.until(ExpectedConditions.elementToBeClickable(By.linkText("To connect")));
}
}
//does not work
driver.findElements(By.linkText("next")).click();
//does not work
((org.openqa.selenium.WebElement)driver.findElements(By.linkText("next"))).click();
your click function is not coming because driver.findElements(By.linkText("next")) returns a list List<WebElement> and click() cant be called on a list object .
you can call click method my iterating over the list :
List<WebElement> WebElementList = driver.findElements(By.linkText("next"));
for(WebElement element : WebElementList){
element.click(); // click can be called on object of WebElement
}
I modified the code to iterate through google search results pages and to get the results' URLs.
public static void searchGoogle(String query) throws InterruptedException {
try {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.co.uk");
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("\"" + query + "\" filetype:pdf\n");
element.submit();
// wait until the google page shows the result
WebElement myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));
getResults(driver);
Thread.sleep(1000);
for (int i = 0; i < 10; i++) {
driver.findElement(By.linkText("Next")).click();
Thread.sleep(1000);
getResults(driver);
}
} catch (Exception e) {
System.err.println("Error caught - " + e);
}
}
public static void getResults(WebDriver driver) {
List<WebElement> findElements = null;
findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements) {
System.out.println(webElement.getAttribute("href"));
}
}
It should be driver.findElement(By.linkText("next")).click();. driver.findElements returns List<WebElement> while driver.findElement returns single WebElement.
Also, it seems the button doesn't have next text. Try looking by class
driver.findElement(By.className("next")).click();
next text will look like
<a class="page-link" href="next" title="next" data-li-page="next">"next"</a>
with next before the <a> closing tag.

How to verify the button having drop down menu using selenium in java

There is a button. When you click on this button, a drop down menu having two option appears. How to verify this scenario using selenium in java.
<div class="hpDropDownButton">
<button class="button ng-binding">Holidays Operation</button>
<ul>
<li>
<a class="ng-binding" ng-click="uploadHolidays()">Upload Holidays</a>
</li>
<li>
<a class="ng-binding" ng-click="deleteHolidays()">Delete Holidays</a>
</li>
</ul>
Click on the button
Now :-
Boolean dropdownPresent = driver.findElement("YOUR LOCATOR OF DROPDOWN").isDisplayed();
if(dropdownPresent==true)
{
System.out.println("Dropdown is appearing");
}
else{
System.out.println("Dropdown is not appearing");
}
Hope it will help you :)
You are asking to verify whole scenario. You need to first understand what Selenium-WebDriver is. Refer this tutorial for more explanation.
However you can follow below code,
WebDriver driver = new FirefoxDriver();
String appUrl = "your url";
driver.get(appUrl);
// maximize the browser window
driver.manage().window().maximize();
// upto code from your button
WebElement button_element = driver.findElement(button_locator);
button_element.click();
// to verify a drop down menu having two option appears
boolean flag = isPresent(dropdown_locator);
if (flag) {
// code bases on dropdown displayed
}
else {
// code bases on dropdown not displayed
}
To verify if element is present or not use this method
public boolean isPresent(String locator) {
return findElements(locator).size() > 0 ? true : false;
}
First of all collect all the Drop down values in List, List values = Upload Holidays#Delete Holidays
Then click on Dropdown WebElement, by using DropdownFieldName = driver.findElement(by.xpath(//button[#class='button ng-binding'])).click();
Take the couunt of dropdown values, by drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
Now you have expected DropDown values and count of Dropdown Values.
You can take a reference from below code:
checkDropDownValues(String DropdownFieldName, String values){
driver.findElement(By.xath(DropdownFieldName)).click();
WebElement drptotalCount = driver.findElements(by.xpath(//a[#class='button ng-binding']));
int numberOfDropDown = drptotalCount.size();
List<String> allDropDownValues = Arrays.asList(values.split("#"));
for (int colCount = 1; colCount <= numberOfDropDown; colCount++) {
boolean flag = false;
Actualvalue = driver.findElement(By.xpath(drptotalCount + "[.=" + allDropDownValues.get(colCount) +"]"])).getText();
String expectedValues = allDropDownValues.get(colCount);
if(expectedValues.equalIgnoreCase(Actualvalue))
{
flag = true;
}
Assert.assertTrue("Column values doesn't match", flag);
}
}
Click the button (which should be straight forward)
it seems you have some asynchronous call or a delay
Wait for the drop-down 'div.hpDropDownButton' is beeing displayed using WebDriverWait:
WebElement myDynamicDropDown = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.CssSelector("div.myDynamicDropDown")))
continue ..
http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

Select Radio Button in a group using Selenium WebDriver with Java

I want to be able to select a radio button within a group (of radio buttons) identified by the name attribute:
<div>
<input type="radio" name="exampleInputRadio" id="optionRadio1" value="1">
<input type="radio" name="exampleInputRadio" id="optionRadio2" value="2">
<input type="radio" name="exampleInputRadio" id="optionRadio3" value="3">
<input type="radio" name="exampleInputRadio" id="optionRadio4" value="4">
</div>
I use the following code to do what I want:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
The problem is that Selenium always selects the first radio button, no matter the value of option argument is.
And when I code this in the above method:
for (int i = 0; i < radios.size(); i++) {
System.out.println(radios.get(i).getAttribute("id"));
}
I get this output:
optionRadio1
optionRadio2
optionRadio3
optionRadio4
The code is absolutely working fine for me on Firefox 28.
I have tried something like this:
function:
public void exampleInputRadio(WebDriver driver, int option) {
List<WebElement> radios = driver.findElements(By.name("exampleInputRadio"));
if (option > 0 && option <= radios.size()) {
radios.get(option - 1).click();
} else {
throw new NotFoundException("option " + option + " not found");
}
}
functions called:
TestClass tc = new TestClass();
tc.exampleInputRadio(driver, 1);
tc.exampleInputRadio(driver, 2);
tc.exampleInputRadio(driver, 3);
tc.exampleInputRadio(driver, 4);
A simple work around could be using the value or the id attributed.
driver.findElement(By.id("optionRadio" + (option + 1))).click();
Also you can use xpath, something like this:
driver.findElement(By.xpath("//input[#value='1]")).click();

Categories

Resources