How to click on the button as per the HTML provided? - java

This is the html code for the button in the pop up ( pop up has a lead gen form) -
<button id="getCoupon" class="fetch" data-bind="click: submitForm" type="submit">Fetch Coupon</button>
This is the script which I have written in JAVA in Eclipse. I am able to fill the name, Email and Phone number but I'm not able to click on the button -
driver.findElement(By.id("getCoupon")).click();

As per the comment and URL, you have shared :
You can try with this code :
public class Pawan {
static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\user**\\Downloads\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://vets.cm.qa.preview.vca.webstagesite.com/free-first-exam");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("input[value='/santa-monica']~div.select-btn"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.id("fName"))).sendKeys("Pawan");
wait.until(ExpectedConditions.elementToBeClickable(By.id("lName"))).sendKeys("Sharma");
wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("ps12#gmail.com");
wait.until(ExpectedConditions.elementToBeClickable(By.id("zip"))).sendKeys("90404");
wait.until(ExpectedConditions.elementToBeClickable(By.id("phone"))).sendKeys("9697989900");
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,100)", "");
wait.until(ExpectedConditions.elementToBeClickable(By.id("getCoupon"))).click();
}
}

As per your HTML code, your id is : "getCoupon",
whereas in code you mentioned id as : "getCouponFetch". Please correct and it should work. Code -
driver.findElement(By.id("getCoupon")).click();
If selenium click don't work, use below Java Script click code :
WebElement element = driver.findElement(By.id("getCoupon")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", element);

Firstly, what kind of error did you get??
Try using implicit wait if your getting "NoSuchElementException" like below:
driver.manage().timeOuts().implicitlywait(30,TimeUnit.SECONDS);
Then try using the below way to locate that button:
driver.findElementByXpath("text()[contains(.,'Fetch Coupon')]").click();

As per the HTML you have shared to click() on the button you have to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon"))).click();
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]"))).click();
Update
As an alternative you can use the executeScript() method to invoke the click() as follows:
Using cssSelector:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.fetch#getCoupon")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);
Using xpath:
WebElement fetch_coupon = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='fetch' and #id='getCoupon'][contains(.,'Fetch Coupon')]")));
((JavascriptExecutor)driver).executeScript("arguments[0].click();", fetch_coupon);

Related

Element Clickable in Java Selenium

I'm trying to click on Calendar but everytime I try to click on the calendar the error pop up as "element click intercepted: Element is not clickable at point (293, 1317)
<input type="text" name="form_fields[travel_comp_date]" id="form-field-travel_comp_date"
class="elementor-field elementor-size-sm elementor-field-textual elementor-date-field
flatpickr-input" placeholder="Date of travel"
pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" readonly="readonly">
Here's my code:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#name='form_fields[travel_comp_date]']")));
driver.findElement(By.xpath("//input[#name='form_fields[travel_comp_date]']")).click();
Can someone please help me correcting this.
Please try the following code with explicit wait and let me know if it works for you:
enter code here
driver.get("https://www.path2usa.com/travel-companion/");
WebElement dateTravel =
driver.findElement(By.xpath("//input[#id='form-field-
travel_comp_date']"));
driver.manage().window().maximize();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,1000)");
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(5));
js.executeScript("arguments[0].scrollIntoView();", dateTravel);
wait.until(ExpectedConditions.visibilityOf(dateTravel));
if(dateTravel.isDisplayed())
{
js.executeScript("document.getElementById('form-field-
travel_comp_date').value='12/20/2023'");
}
The element you are trying to access is out of the initially presented view port.
In order to click it you first need to scroll the page to bring that element into the visible view port and only after that you will be able to click on it.
Please try this:
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");
Or this
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,600)");
After that try performing your code

Click the Button and get the size of table in Selenium java

I am trying to learn selenium to find elements and I could not clicking the "Edit"buttons and Im trying the get the size of the rows of the table.
Here is my code:
System.setProperty("webdriver.chrome.driver","C:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String baseUrl = "https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/PopupEditing/Angular/Light/";
driver.get(baseUrl);
driver.manage().window().maximize();
TimeUnit.SECONDS.sleep(5);
List<WebElement> we = driver.findElements(By.linkText("Edit")); System.out.println(we.size());
we.get(1).click();
Here is the link that I am working:
https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/PopupEditing/Angular/Light/
driver = new ChromeDriver();
driver.get("https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/PopupEditing/Angular/Light/");
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
WebElement frame = wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.id("demoFrame"))));
driver.switchTo().frame(frame);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("[class=\"dx-link dx-link-edit\"]"))).click();
Use webdriver wait and switchTo frame, you have to switch to iframe first to interacte elements inside the iframe.
once you finish , if you want to interact with elements outside iframe then you have to switch out of it first.
driver.switchTo().defaultContent();
//rest of your code
The element is present inside an iframe and you need to switch iframe first and then you will be able to interact with element.
To overcome synchronization issue you need to induce WebDriverWait() and wait for frameToBeAvailableAndSwitchToIt() and following locator.
To get the link details induce WebDriverWait() and wait for visibilityOfAllElementsLocatedBy() and following locator.
WebDriver driver = new ChromeDriver();
String baseUrl = "https://js.devexpress.com/Demos/WidgetsGallery/Demo/DataGrid/PopupEditing/Angular/Light/";
driver.get(baseUrl);
driver.manage().window().maximize();
new WebDiverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("demoFrame")));
List<WebElement> we =new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.linkText("Edit")));
System.out.println(we.size());
we.get(1).click();

Button not clickable consistently in Selenium Java

I am trying to click a button in selenium java code and it is not clicking all the time. Apparently this is pretty common issue.
I tried below few solutions:
HTML Code :
<button class="btn btn--action btn--border-white btn--my__calculate" style="display: inline-block;">Final Figure</button>
Solution 1:
WebElement btnWorkout = webDriver.findElement(By.cssSelector(".btn--my__calculate"));
if (btnWorkout.isDisplayed() && btnWorkout.isEnabled()) {
btnWorkout.click();
}
Solution 2 :
WebDriverWait wait = new WebDriverWait(webDriver, 10);
WebElement btnWorkout = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".btn--my__calculate")));
btnWorkout.click();
Solution 3:
WebElement btnWorkout = webDriver.findElement(By.cssSelector(".btn--my__calculate"));
JavascriptExecutor executor = (JavascriptExecutor) webDriver;
executor.executeScript("arguments[0].click();", btnWorkout);
None of them worked for me.
Other strange thing is above step passes without an error and button doesn't click as expected
Induce WebDriverWait And Following Xapth.
Try following options.
Option1:
WebDriverWait wait = new WebDriverWait(webDriver, 20);
WebElement btnWorkout=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='btn btn--action btn--border-white btn--my__calculate'][text()='Final Figure']")));
btnWorkout.click();
Option2: Use Action class
WebDriverWait wait = new WebDriverWait(webDriver, 20);
WebElement btnWorkout=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='btn btn--action btn--border-white btn--my__calculate'][text()='Final Figure']")));
Actions action=new Actions(webDriver);
action.moveToElement(btnWorkout).click().build().perform();
Option3: Use JavaScript Executor
WebDriverWait wait = new WebDriverWait(webDriver, 20);
WebElement btnWorkout=wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[#class='btn btn--action btn--border-white btn--my__calculate'][text()='Final Figure']")));
JavascriptExecutor executor = (JavascriptExecutor) webDriver;
executor.executeScript("arguments[0].click();", btnWorkout);
Curious that the executeScript() option didn't work for you. Keep using your WebDriverWait from option 2, but instead of the click() method, try using Action Chains. I'm not sure how to write this in Java, but it'll be something like this:
Actions action = new Actions(driver);
action.move_to_element(btnWorkout).click(btnWorkout).perform();
Maybe you have another hidden element with same CSS (class). You can try capture the element by linkText or partialLinkText like this:
WebElement btnWorkout = webDriver.findElement(By.linkText("Final Figure"));

How to select an option from a dynamic dropdown using Selenium?

I am trying to click on dropdown value to select city in from field in Make my trip http://www.makemytrip.com/. But getting Stale element reference exception. Ids are getting changed on page load.
Tried below code:
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[#id='ui-id-1']"));
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeSelected(driver.findElement(By.xpath(".//*[#class='ui-menu-item'][2]"))));
To click on a dropdown value e.g. Mumbai you can use the following solution:
Code Block:
driver.get("https://www.makemytrip.com/")
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='input_fromto checkSpecialCharacters ui-autocomplete-input' and #id='hp-widget__sfrom']"))).click();
List<WebElement> myList = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//li[#class='ui-menu-item'][starts-with(#id,'ui-id-')]//span[#class='autoCompleteItem__label']")));
for (WebElement element:myList)
if(element.getText().contains("Mumbai"));
element.click();
Browser Snapshot:
You can use this working code:
WebDriver driver = new ChromeDriver();
driver.get("https://www.makemytrip.com/");
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).clear();
driver.findElement(By.xpath(".//*[#id='hp-widget__sfrom']")).click();
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#class='ui-menu-item'][2]/div/p[1]/span[1]"))).click();
I have fixed the xPath of dropdown list element. Always try to specify the exact element yo want to interact with. For example if you want to click on button, try to find <span> or <button> tag, for a link <a> tag and for input fields <input> tag.
You can try this code :
I do not see any use of xpath in this scenario. I have converted some of the xpath to either css selector or id. and have kept only one. Though I have not faced any stale element reference.
System.setProperty("webdriver.chrome.driver", "D:\\Automation\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get("https://www.makemytrip.com/");
WebElement from = wait.until(ExpectedConditions.elementToBeClickable(By.id("hp-widget__sfrom")));
from.click();
from.clear();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("ul[class*='ui-widget-content hp-widget__sfrom']")));
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[contains(#aria-label,'Top Cities : Mumbai, India ')]"))).click();
The below code works fine for me and it is parameterized as well, it works for any input value without changing the xpath. In this example, I took mumbai as test data.
driver.get("https://www.makemytrip.com/");
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).clear();
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).click();
driver.findElement(By.xpath("//input[contains(#id,'hp-widget__sfrom')]")).sendKeys("Mumbai");
Thread.sleep(2000);
WebDriverWait wait = new WebDriverWait(driver, 30);
By option = By.xpath("//div[#class='autoCompleteItem']/p/span[contains(text(),'Mumbai')]");
wait.until(ExpectedConditions.elementToBeClickable(option));
driver.findElement(option).click();

How to handle AutoSearch completion using Selenium webdriver

I am running Selenium Web-driver using JAVA and facing an issue with auto-suggest input text field. When I enter a String "books" in the text field, an option would show up. Then I want to click or select the input populated on the auto suggest menu.
Below is the code:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.amazon.com/");
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("books");
WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("gwcswTooltip")));
List<WebElement> findElements = driver.findElements((By.id("gwcswTooltip").name("books on")));
for (WebElement webElement : findElements)
{
System.out.println(webElement.getText());
}
You need to just pick the right locator.
Add the following line
List<WebElement> findElements = driver.findElements((By.xpath("//div[#id='srch_sggst']/div")));
instead of
List<WebElement> findElements = driver.findElements((By.id("gwcswTooltip").name("books on")));

Categories

Resources